- Программист — это звучит гордо
- Страницы
- вторник, 14 июня 2016 г.
- Оптимизация работы с SSD: Планировщики ввода/вывода в Linux
- Теоретическая часть
- Noop I/O Scheduler
- Deadline I/O Scheduler
- Anticipatory I/O Scheduler
- Complete Fair Queuing (CFQ) I/O Scheduler
- Выбор планировщика
- Практическая часть
- Тестирование
- Linux Change The I/O Scheduler For A Hard Disk
- Task: View Current Disk scheduler
- Task: Set I/O Scheduler For A Hard Disk
- Ubuntu Wiki
- IOSchedulers
- Multiqueue I/O schedulers
- bfq (Budget Fair Queuing) (Multiqueue)
- kyber (Multiqueue)
- none (Multiqueue)
- mq-deadline (Multiqueue)
- Non-multiqueue I/O schedulers
- deadline
- cfq (Completely Fair Queueing)
- noop (No-operation)
- Selecting I/O Schedulers
- Tuning I/O Schedulers
- Best I/O scheduler to use
- SSD or NVME drives
Программист — это звучит гордо
Знаниями нужно делиться, иначе они протухают.
Страницы
вторник, 14 июня 2016 г.
Оптимизация работы с SSD: Планировщики ввода/вывода в Linux
Теоретическая часть
Хотя я и упоминал о SSD, но что бы глубже понять тему прийдётся начинать с HDD. Их главная проблема долгое время доступа к произвольному месту на диске. Оно складывается из времени позиционирования головки на дорожке и время ожидания поворота диска на угол необходимый для доступа к сектору. Для понимания масштабов бедствия — переключение на другую дорожку в пределах одного цилиндра занимает порядка 1 миллисекунды, переход на соседний цилиндр 2-4 ms. Время оборота диска (7200 rpm) — составляет 8 ms. Для современных дисков время произвольного доступа колеблется от 2.5 до 16 ms — это время, за которое винчестер гарантированно выполнит операцию чтения или записи на любом участке магнитного диска. С проблемой активно борются производители жёстких дисков, например одна из применяемых оптимизаций — упреждающее чтение, в расчёте на то, что следующая команда чтения будет из этой же области диска.
Следующий нюанс — архитектура программ. Чтение обычно синхронная операция, пока мы не получили данные, продолжать работу мы не можем. А вот запись напротив чаще всего асинхронно и приложению не так важно когда реально будут записаны эти данные. Поэтому желательно, что бы запросы на чтение выполнялись как можно быстрее, а вот запись можно отложить на какое-то время.
Теперь имея представление о проблемах, рассмотрим, как планировщики ввода/вывода их решают. В современных дистрибутивах обычно из коробки присутствуют 4 планировщика:
Noop I/O Scheduler
Deadline I/O Scheduler
Каждому входящему запросу назначается предельное время (deadline) через сколько он должен быть выполнен. Для чтения это по умолчанию 500 ms, для записи 5 сек. Все новые запросы пишутся в одну из двух очередей — FIFO очередь на чтение и FIFO очередь на запись. Таким образом в голове каждого из списков храниться запрос, у которого deadline ближе всего. Так же запрос вставляется ещё и в общую очередь, отсортированную так, что бы минимизировать кол-во перемещений головки диска (фактически по номеру блока).
При записи на диск, планировщик проверяет первые две очереди, если есть запросы с истёкшим deadline — выполняет их в первую очередь. В противном случае берёт запросы из общей, отсортированной, очереди.
Anticipatory I/O Scheduler
Упреждающий планировщик. Он пытается решить некоторые проблемы предыдущего. Как я уже говорил, приложения обычно читают данные с диска в синхронном режиме — прочитали кусок из файла и только потом запрашивают следующий. Это приводит к тому, что после выполнения первого запроса на чтение, планировщик переключается к выполнению других запросов и головка диска «уходит» в другое место. А приложение шлёт следующий запрос, который с большой долей вероятности расположен рядом с предыдущим. Если бы планировщик подождал немного, он бы смог быстро обслужить и этот запрос.
Вот такое ожидание этот планировщик и добавляет. Он после каждого запроса на чтение, 6 ms ждёт следующего запроса от приложения, если ничего не получил, продолжает работать как deadline scheduler.
Complete Fair Queuing (CFQ) I/O Scheduler
Выбор планировщика
Нет единого ответа на вопрос какой из планировщиков лучше. Каждый из них имеет сильные и слабые стороны и поэтому нужно смотреть на характер нагрузки, отношение операций записи к чтению и т.п. Разве что noop scheduler будет для HDD гарантированно плохим выбором.
Вот допустим Red Hat в своей статье называет лучшим CFQ и приводит такой график:
А IBM с этим мнением не согласена и считает, что Deadline лучше других:
Практическая часть
С теорией разобрались, переходим к практике. Стоит предупредить, что я проверял инструкцию ниже только на Arch Linux. И хотя я не использовал ничего специфичного, но гарантировать работу на всех дистрибутивах не могу, проверяйте сначала на виртуальной машине.
Посмотреть список поддерживаемых планировщиков, например для sda:
Стоит помнить, что выбранный планировщик вступит в действие не сразу, а через некоторое время. И работать настройка будет до перезагрузки. Что бы установить другой умолчательный планировщик для всех дисков, добавте параметр ядра «elevator=scheduler_name».
Покажу на примере GRUB и планировщика «deadline». Откройте «/etc/default/grub» и добавьте в «GRUB_CMDLINE_LINUX_DEFAULT» нужный параметр, у меня получилось вот так:
Тестирование
Сложная тема, для любого планировщика можно подобрать такой набор тестов, который покажет что именно он самый быстрый. Один лучше обслужит одно приложение читающее большие файлы, другой покажет свою мощь на множестве мелких параллельных чтений и т.д. Параметров который влияют на производительность неприлично много.
И если вы например проверите скорость копирования файлов, то результат покажет лишь как быстро с данным планировщиком копируются файлы. Если это у вас основной паттерн использования диска — то это адекватный тест, в противном случае он ни о чём.
Могу порекомендовать статью на тему, на мой взгляд очень обстоятельную. Там же вы найдёте методику тестирования при помощи утилиты fio. Пересказывать не буду, поскольку в статье и так всё достаточно хорошо описано.
Источник
Linux Change The I/O Scheduler For A Hard Disk
H ow do I change the I/O scheduler for a particular hard disk without rebooting my Linux server system?
CFQ [cfq] (Completely Fair Queuing) is an I/O scheduler for the Linux kernel and default under many Linux distributions.
Noop scheduler (noop) is the simplest I/O scheduler for the Linux kernel based upon FIFO queue concept.
Anticipatory scheduler (anticipatory) is an algorithm for scheduling hard disk input/output as well as old scheduler which is replaced by CFQ
Deadline scheduler (deadline) – it attempt to guarantee a start service time for a request.
- 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 ➔
Task: View Current Disk scheduler
Assuming that your disk name /dev/sda, type:
# cat /sys/block/< DEVICE-NAME >/queue/scheduler
# cat /sys/block/ sda /queue/scheduler
Sample output:
Task: Set I/O Scheduler For A Hard Disk
To set a specific scheduler, simply type the command as follows:
# echo < SCHEDULER-NAME >> /sys/block/< DEVICE-NAME >/queue/scheduler
For example, set noop scheduler, enter:
# echo noop > /sys/block/hda/queue/scheduler
🐧 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 do i change the scheduler in general?
Edit /boot/grub/grub.conf and enter in kernel line elevator=noop or any other scheduler available.
Kernel compilation should also be a way I think.
Thank you newbie. 🙂
You can echo to /sys/block//queue/scheduler/
e.g. If you want the scheduler to be ‘noop’ for ‘sda’, you should run:
# echo noop > /sys/block/sda/queue/scheduler
“But I’m on Ubuntu, and I want to do it without enabling the root account or running sudo su –:
echo anticipatory | sudo tee /sys/block/sdb/queue/scheduler
Also note that, if you’re using lvm, you’ll have the physical devices (like sda) as well as the virtual devices (like dm-1). Same goes for software raid – you’ll have md0, etc. It’s unclear to me which setting wins if you are running lvm on top of software raid (which isn’t incredibly uncommon), and have different schedulers set for the physical disks, raid devices, and lvm devices…
PS: it looks like you can find out which LVM volume maps to “dm-6”, for example, by dong an ls -l on /dev/block/252:*. On one of my machines, I get
lrwxrwxrwx 1 root root 18 2009-12-12 21:53 /dev/block/252:6 -> ../mapper/pyro-var
Which indicates that dm-6 is currently the “var” volume in the “pyro” volume group.
How to change the linux scheduler for user fairness .
I cant find device name of my attached device in /sys/block/ since its attached external drive. Therefore I cant see current io-scheduler for this disk.
Please help.
@Kedar: you would need to specify how exactly the external disk is attached
we can automate this step for every reboot by:
cat /etc/rc.local | grep -iv “^exit” > /tmp/temp
echo -e “echo deadline > /sys/block/vda/queue/scheduler\nexit 0” >> /tmp/temp
cat /tmp/temp > /etc/rc.local; rm /tmp/temp
as u can see i used deadline for vda in this example.
it simply ignore “exit” line and add deadline command to reboot script.
Advice from a cat grepper should generally be avoided.
I did: “cat /sys/block/sda/queue/scheduler”
The output is: “noop deadline [cfq]”
What does it mean?
Is my current elevator ‘noop’, ‘deadline’ or ‘cfq’?
Thanks
Источник
Ubuntu Wiki
IOSchedulers
I/O schedulers attempt to improve throughput by reordering request access into a linear order based on the logical addresses of the data and trying to group these together. While this may increase overall throughput it may lead to some I/O requests waiting for too long, causing latency issues. I/O schedulers attempt to balance the need for high throughput while trying to fairly share I/O requests amongst processes.
Different approaches have been taken for various I/O schedulers and each has their own set of strengths and weaknesses and the general rule is that there is no perfect default I/O scheduler for all the range of I/O demands a system may experience.
Multiqueue I/O schedulers
Note: These are the only I/O schedulers available in Ubuntu Eoan Ermine 19.10 and onwards.
The following I/O schedulers are designed for multiqueue devices. These map I/O requests to multiple queues and these are handled by kernel threads that are distributed across multiple CPUs.
bfq (Budget Fair Queuing) (Multiqueue)
Designed to provide good interactive response, especially for slower I/O devices. This is a complex I/O scheduler and has a relatively high per-operation overhead so it is not ideal for devices with slow CPUs or high throughput I/O devices. Fair sharing is based on the number of sectors requested and heuristics rather than a time slice. Desktop users may like to experiment with this I/O scheduler as it can be advantageous when loading large applications.
kyber (Multiqueue)
Designed for fast multi-queue devices and is relatively simple. Has two request queues:
- Synchronous requests (e.g. blocked reads)
- Asynchronous requests (e.g. writes)
There are strict limits on the number of request operations sent to the queues. In theory this limits the time waiting for requests to be dispatched, and hence should provide quick completion time for requests that are high priority.
none (Multiqueue)
The multi-queue no-op I/O scheduler. Does no reordering of requests, minimal overhead. Ideal for fast random I/O devices such as NVME.
mq-deadline (Multiqueue)
This is an adaption of the deadline I/O scheduler but designed for Multiqueue devices. A good all-rounder with fairly low CPU overhead.
Non-multiqueue I/O schedulers
NOTE: Non-multiqueue have been deprecated in Ubuntu Eoan Ermine 19.10 onwards as they are no longer supported in the Linux 5.3 kernel.
deadline
This fixes starvation issues seen in other schedulers. It uses 3 queues for I/O requests:
- Sorted
- Read FIFO — read requests stored chronologically
- Write FIFO — write requests stored chronologically
Requests are issued from the sorted queue inless a read from the head of a read or write FIFO expires. Read requests are preferred over write requests. Read requests have a 500ms expiration time, write requests have a 5s expiration time.
cfq (Completely Fair Queueing)
- Per-process sorted queues for synchronous I/O requests.
- Fewer queues for asynchronous I/O requests.
- Priorities from ionice are taken into account.
Each queue is allocated a time slice for fair queuing. There may be wasteful idle time if a time slice quantum has not expired.
noop (No-operation)
Performs merging of I/O requests but no sorting. Good for random access devices (flash, ramdisk, etc) and for devices that sort I/O requests such as advanced storage controllers.
Selecting I/O Schedulers
Prior to Ubuntu 19.04 with Linux 5.0 or Ubuntu 18.04.3 with Linux 4.15, the multiqueue I/O scheduling was not enabled by default and just the deadline, cfq and noop I/O schedulers were available by default.
For Ubuntu 19.10 with Linux 5.0 or Ubuntu 18.04.3 with Linux 5.0 onwards, multiqueue is enabled by default providing the bfq, kyber, mq-deadline and none I/O schedulers. For Ubuntu 19.10 with Linux 5.3 the deadline, cfq and noop I/O schedulers are deprecated.
With the Linux 5.0 kernels, one can disable these and fall back to the non-multiqueue I/O schedulers using a kernel parameter, for example for SCSI devices one can use:
..add this to the GRUB_CMDLINE_LINUX_DEFAULT string in /etc/default/grub and run sudo update-grub to enable this option.
Changing an I/O scheduler is performed on a per block device basis. For example, for non-multi queue device /dev/sda one can see the current I/O schedulers available using the following:
to change this to deadline use:
For multiqueue devices the default will show:
To use kyber, install the module:
To use bfq, install the module:
Tuning I/O Schedulers
Each I/O scheduler has a default set of tunable options that may be adjusted to help improve performance or fair sharing for your particular use case. The following kernel documentation covers these per-I/O scheduler tunable options:
Best I/O scheduler to use
Different I/O requirements may benefit from changing from the Ubuntu distro default. A quick start guide to select a suitable I/O scheduler is below. The results are based on running 25 different synthetic I/O patterns generated using fio on ext4, xfs and btrfs with the various I/O schedulers using the 5.3 kernel.
SSD or NVME drives
It is worth noting that there is little difference in throughput between the mq-deadline/none/bfq I/O schedulers when using fast multi-queue SSD configurations or fast NVME devices. In these cases it may be preferable to use the ‘none’ I/O scheduler to reduce CPU overhead.
Avoid using the none/noop I/O schedulers for a HDD as sorting requests on block addresses reduce the seek time latencies and neither of these I/O schedulers support this feature. mq-deadline has been shown to be advantageous for the more demanding server related I/O, however, desktop users may like to experiment with bfq as has been shown to load some applications faster.
Of course, your use-case may differ, the above are just suggestions to start with based on some synthetic tests. You may find other choices with adjustments to the I/O scheduler tunables produce better results.
Kernel/Reference/IOSchedulers (последним исправлял пользователь colin-king 2019-09-10 16:33:33)
Источник