Iowait что это
Перейти к содержимому

Iowait что это

  • автор:

What is iowait and how does it affect Linux performance?

iowait (wait, wa, %iowait, wait%, or I/O wait) is often displayed by command-line Linux system monitoring tools such as top, sar, atop, and others. On its own, it’s one of many performance stats that provide us insight into Linux system performance.

I/O wait came up in a recent discussion with a new client. During our support call, they reported load spikes of 60 to 80 on their 32 CPU core system. This resulted in slow page loading, timeouts, and intermittent outages. The cause? Storage I/O bottleneck was initially hinted at by a consistently high iowait and later confirmed with additional investigation.

What is I/O wait? How does I/O wait affect Linux server performance? How can we monitor and reduce I/O wait related issues? Continue reading for the answers to these questions.

iowait example - using iostat

iowait example 1 – using iostat.

What is iowait?

I/O wait (iowait) applies to Unix and all Unix-based systems, including macOS, FreeBSD, Solaris, and Linux.

I/O wait is the percentage of time that the CPU (or CPUs) were idle during which the system had pending disk I/O requests. (Source: man sar ) The top command’s man page gives this simple explanation: “I/O wait = time waiting for I/O completion.” In other words, the presence of I/O wait tells us that the system is idle when it could be processing outstanding requests.

“iowait shows the percentage of time that the CPU or CPUs were idle during which the system had an outstanding disk I/O request.” – iostat man page.

When using Linux top and other tools, you’ll notice that a CPU (and its cores) operate in the following states:

Of these, the ‘user’, ‘system’, ‘idle’, and ‘wait’ values should add up to 100%. Note that “idle” and “wait” are not the same. “Idle” CPU means there is no workload present while, on the other hand, “wait” (iowait) indicates when the CPU is waiting in an idle state for outstanding/waiting requests.

If the CPU is idle, the kernel will ascertain any pending I/O requests (i.e., NVMe or NAS) originating from the CPU. If there are, then the ‘iowait’ counter is incremented. If nothing is pending, then the ‘idle’ counter is incremented.

iowait and Linux server performance

It’s important to note that iowait can, at times, indicate a bottleneck in throughput, while at other times, iowait may be completely meaningless. It’s possible to have a healthy system with some iowait, but also possible to have a bottlenecked system without iowait.

I/O wait is simply one of the indicated states of your CPU and CPU cores. A high iowait means your CPU is waiting on requests, but you’ll need to investigate further to confirm the source and effect.

For example, server storage is almost always slower than CPU performance. Because of this, I/O wait may be misleading, especially when it comes to random read/write workloads. Iowait only measures CPU performance, not storage I/O.

Although iowait indicates that the CPU can handle more workload, depending on your server’s workload and how load performs computations or makes use of storage I/O, it isn’t always possible to solve I/O wait. Nor is it always feasible to achieve a zero value.

Based on end-user experience, database health, transaction throughput, and overall application health, you will have to decide whether or not the iowait reported indicates poor Linux system performance.

For example, if you see an iowait of 1 to 4 percent, and you then upgrade the CPU to 2x the performance, the iowait will also increase. A 2x faster CPU with the same storage performance = ~ 2x the wait. You’ll want to consider your workload to determine which hardware you should pay attention to first.

Monitoring and reducing I/O wait related issues

iostat -xm 2 (check for iowait)

Using iostat -xm 2 to check for iowait.

Let’s look at some valuable tools used to monitor I/O wait on Linux.

  • atop – run it with -d option or press d to toggle the disk stats view.
  • iostat – try it with the -xm 2 options for extended statistics, in megabytes and in two-second intervals.
  • iotop – top-like I/O monitor. Try it with the -oPa options to show the accumulated I/O of active processes only.
  • ps – use auxf , then under the “STAT” column “D” usually indicates disk iowait.
  • strace – view the actual operations issued by a process. Read the strace man page.
  • lsof – after you’ve identified the process responsible, use -p [PID] to find the specific files.

Reducing I/O wait related issues.

Take the following steps to reduce I/O wait related issues.

  • Optimize your application’s code and database queries. This can go a long way in reducing the frequency of disk reads/writes. This should be your first approach because the more efficient your application is, the less you’ll have to spend on hardware long-term. See also: 100 Application Performance Monitoring (APM) & Observability Solutions.
  • Keep your Linux system and software versions up-to-date. Not only is this better for security, but more often than not, the latest supported versions offer notable performance improvements, whether it’s Nginx, Node.js, PHP, Python, or MySQL.
  • Make sure that you have free memory available. Enough free memory so that around half of the server’s memory is being used for in-memory buffers and cache, rather than swapping and paging to disk. Of course, this ratio will differ case by case. Therefore, be sure you are not swapping and kernel cache pressure isn’t high due to a lack of free memory.
  • Tweak your system, storage device(s), and the Linux kernel for increased storage performance and lifespan.
  • Finally, if all else fails, upgrade storage devices to faster SSD, NVMe, or other high-throughput storage devices.

Conclusion

Understanding and managing I/O wait (iowait) is crucial for maintaining the optimal performance of Linux servers. Iowait represents the percentage of time that the CPU is idle while waiting for pending disk I/O requests, making it a valuable metric in system monitoring. However, interpreting iowait requires careful consideration of your server’s workload and application performance.

It’s important to note that high iowait doesn’t always indicate a problem, as modern storage solutions may inherently be slower than CPU performance. The key is to investigate further and assess the impact on end-user experience, database queries, and overall application health.

To effectively monitor and address I/O wait related issues, you can utilize various tools such as atop, iostat, iotop, pstree, ps, strace, and lsof. These tools help identify the processes responsible for high iowait and provide insights into potential optimizations.

Reducing I/O wait involves optimizing your application’s code and database queries, keeping your Linux system and software up-to-date, ensuring sufficient free memory, and tweaking system and storage settings. In extreme cases, upgrading to faster storage devices like SSDs or NVMe can significantly improve performance.

In addition to the tracing tools mentioned above, we can use observability and benchmarking tools to put together a complete picture of the system’s overall I/O performance. Your main goal should be to reduce or eliminate any iowait directly resulting from waiting storage-related I/O.

Published: Aug 19th, 2020 | Last updated: October 2nd, 2023.

Заметки о Unix: проблема iowait и многопроцессорные системы

В разных Unix-системах уже давно имеется показатель iowait. Я, правда, не могу найти систему, в которой этот показатель появился. Это — не 4.x BSD, поэтому iowait, возможно, добрался до современных систем через System V и sar . Традиционным, стандартным определением iowait является время, которое система проводит в бездействии, когда в ней имеется хотя бы один процесс, ожидающий окончания операции дискового ввода-вывода. Вместо того чтобы относить это время к категории idle (простой процессора) (когда процессорное время делится на три категории — user, system и idle), в некоторых Unix-системах это время стали относить к новой категории — iowait.

(К моему удивлению оказалось, что понятия «iowait», похоже, нет ни в одной *BSD-системе. Там используется старая схема user-system-idle и детализация системного времени. Iowait имеется в Linux и в Solaris/Illumos, этот показатель, если верить результатам беглого просмотра справки, есть ещё в HP-UX и в AIX.)

Вышеприведённое определение iowait выглядит совершенно осмысленным и понятным на однопроцессорной машине, где система не может одновременно и пребывать в состоянии бездействия, ожидая, когда процесс завершит операцию ввода-вывода, и выполнять другой процесс. Но в наши дни практически все компьютеры представляют собой многопроцессорные «SMP», а в многопроцессорной среде способ определения показателя iowait уже далеко не так прост, так как там нет чёткого разделения между «выполняющимся кодом» и «кодом, остановленным в ожидании завершения операции ввода-вывода». В многопроцессорных системах некоторые процессоры могут быть заняты выполнением кода, а некоторые процессы могут быть заблокированы в ожидании результатов операций ввода-вывода. Если операции ввода-вывода, выполняемые такими процессами, завершаются мгновенно, они, на самом деле, могут выполняться на процессорах, которые в настоящий момент простаивают. Но, в то же время, система занята некоей работой вместо того, чтобы, полностью остановившись, ожидать завершения операции ввода-вывода (а в однопроцессорной системе показатель iowait рассчитывается именно на основании времени, когда система находится в подобном состоянии).

На вопрос о том, что представляет собой iowait в многопроцессорной Unix-системе, можно дать множество правдоподобных ответов. Они могут быть простыми, сложными, или применимыми в некоей конкретной ситуации. Но вне зависимости от того, как именно работает Unix, система должна выдать некий результат (и, в идеале, алгоритм получения этого результата должен быть задокументирован). При этом нет гарантии того, что механизм нахождения показателя iowait будет одним и тем же в разных Unix-системах. Если вы собираетесь серьёзно пользоваться iowait — то вам может понадобиться выяснить то, как именно ваша Unix-система определяет этот показатель в многопроцессорной среде.

(Поиск ответа на вопрос о том, что такое iowait, усложняется в том случае, если используемая вами Unix-система при расчёте iowait ориентируется на отдельные процессоры, как часто бывает с категориями user, system и idle. Дело в том, что обычно ожидание результатов ввода-вывода не связано неким естественным образом с каким-то конкретным процессором. Похоже, что в illumos, если учесть то немногое, что об этом сказано в справке по mpstat, показатель iowait не рассматривается как нечто, относящееся к отдельным процессорам. А справка по sar(1) указывает на то, что в этой системе использован более общий подход к пониманию iowait.)

Пользуетесь ли вы показателем iowait при анализе производительности своих Unix-систем?

  • Unix
  • системное администрирование
  • Блог компании RUVDS.com
  • Настройка Linux
  • Системное администрирование
  • *nix

Системная нагрузка и %iowait

Системная нагрузка

Системная нагрузка – это показатель того, какая нагрузка ложится на микропроцессор(-ы).

Как правило, необходимо, чтобы он держался на уровне ниже 1,0 на микропроцессор или ядро в Вашей системе.

Это значит, что если у Вас четырехъядерная система, как в машине, которую я анализирую, необходимо держать показатель нагрузки на систему ниже 4,0.

%iowait

%iowait – показатель, означающий процентное соотношение времени процессора, потраченное на ожидание ввода/вывода.

Высокий %iowait говорит о том, что Ваша система ограничена возможностями дисковой памяти, выполняя множество операций дискового ввода-вывода, что приводит к замедлению работы системы.

К примеру, если Вашему серверу требовалось бы возвращать 100 или более файлов на каждый запрос, вполне вероятно, это стало бы причиной значительного роста времени %iowait, что означало бы, что диск является узким местом.

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

Два хороших показателя производительности системы – это средняя нагрузка и %iowait. Среднюю нагрузку можно посмотреть с помощью утилиты top, а %iowait — с помощью команды iostat.

Необходимо следить и за top, и за iostat во время теста с длительной нагрузкой, чтобы увидеть, как будут меняться показатели. Давайте запустим top и iostat в отдельных терминалах.

Вас могут заинтересовать другие материалы:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘actions_post_nav’ not found or invalid function name in /var/www/ch8648adac/www/linuxgid.ru/wp-includes/class-wp-hook.php on line 288

высокий iowait, низкая скорость работы дисков

Но вот незадача, в последнее время на первом сервере стал безумно расти iowait % и очевидны тормоза дисковой подсистемы:

top — 10:48:21 up 3:23, 1 user, load average: 8.09, 9.38, 7.10 Tasks: 175 total, 1 running, 174 sleeping, 0 stopped, 0 zombie Cpu(s): 0.2%us, 0.3%sy, 0.0%ni, 53.2%id, 43.7%wa, 0.3%hi, 2.3%si, 0.0%st

[root@www16 www17]# hdparm -t /dev/sda

/dev/sda: Timing buffered disk reads: 4 MB in 3.78 seconds = 1.06 MB/sec [root@www16 www17]# hdparm -t /dev/sdb

/dev/sdb: Timing buffered disk reads: 10 MB in 3.01 seconds = 3.32 MB/sec [root@www16 www17]# hdparm -t /dev/sdb

На втором сервере, даже при нагрузке в 2 раза большей, все ОК: /dev/sda: Timing buffered disk reads: 266 MB in 3.02 seconds = 88.13 MB/sec

Замена одного из дисков на первом сервере результатов не дала — опять все плохо.

Куда посмотреть, чтобы порешить эту проблему? Явно, что конфигурация сервера должна справляться с нагрузкой без проблем (второй сервер-то работает на ура). Конфигурация apache-а одинаковая.

ps. Тормоза начинаются при ~80-100 подключениях к httpd.

moskovitter
09.11.09 20:37:59 MSK

высокий iowait, низкая скорость работы дисков

Сейчас вот этому первому серверу вообще туго:

[root@www16 grub]# w 12:42:56 up 5:18, 2 users, load average: 46.43, 47.63, 44.97 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root pts/0 home 07:25 1:34m 0.23s 0.23s -bash root pts/1 home 11:30 6.00s 0.11s 0.02s w

[root@www16 grub]# hdparm -t /dev/sda

/dev/sda: Timing buffered disk reads: 4 MB in 4.71 seconds = 868.87 kB/sec

105 коннектов на 80й порт У второго сервера — 145 коннекта, но он работает без проблем.

moskovitter
( 09.11.09 20:43:12 MSK ) автор топика

Re: высокий iowait, низкая скорость работы дисков

[телепатия] У тебя деградированный RAID5 из трех дисков?

В dmesg ошибки связанные с дисковой системой есть?

sdio ★★★★★
( 09.11.09 21:50:23 MSK )

высокий iowait, низкая скорость работы дисков

Замена одного из дисков на первом сервере результатов не дала — опять все плохо.

а дисков небось больше трех, и рейд небось железячный. да? я бы контролер поменял в первую очередь, и smartctl-ом по всем винтам.

Komintern ★★★★★
( 09.11.09 22:28:02 MSK )
Ответ на: высокий iowait, низкая скорость работы дисков от Komintern 09.11.09 22:28:02 MSK

высокий iowait, низкая скорость работы дисков

Нету там никаких RAID-ов, на каждом сервере по два диска просто примонтированные в разные точки.

moskovitter
( 09.11.09 23:05:25 MSK ) автор топика
Ответ на: Re: высокий iowait, низкая скорость работы дисков от sdio 09.11.09 21:50:23 MSK

высокий iowait, низкая скорость работы дисков

Нет, никаких ошибок и никакого RAID-а..

moskovitter
( 09.11.09 23:05:56 MSK ) автор топика
Ответ на: высокий iowait, низкая скорость работы дисков от moskovitter 09.11.09 20:43:12 MSK

высокий iowait, низкая скорость работы дисков

Посмотри через iotop, он поподробнее информацию выдаст.

DJAnto ★
( 09.11.09 23:22:28 MSK )
Ответ на: высокий iowait, низкая скорость работы дисков от DJAnto 09.11.09 23:22:28 MSK

высокий iowait, низкая скорость работы дисков

А подскажите, какие параметры и где есть смысл еще посравнивать между двумя серверами. если один дохнет, а другой держит без прооблем нагрузку в 2-3 раза большую? Железо одинаковое, софт тоже, приложения идентичные

moskovitter
( 10.11.09 00:07:00 MSK ) автор топика
Ответ на: высокий iowait, низкая скорость работы дисков от moskovitter 10.11.09 00:07:00 MSK

высокий iowait, низкая скорость работы дисков

Вот еще что нашлось.

[root@www16 ~]# vmstat -S M (Тормозная машина) procs ————memory———- —swap— ——io—- —system— ——cpu—— r b swpd free buff cache si so bi bo in cs us sy id wa st 1 49 0 51 4 1844 0 0 1481 90 133 324 1 3 59 36 0

[root@fast ~]# vmstat -S M (нетормозная машина) procs ————memory———- —swap— ——io—- —system— ——cpu—— r b swpd free buff cache si so bi bo in cs us sy id wa st 0 0 0 50 5 1825 0 0 278 55 3 5 2 4 87 7 0

Видно, что IO/BI разнится в 5 раз.

moskovitter
( 10.11.09 00:17:36 MSK ) автор топика

высокий iowait, низкая скорость работы дисков

PIO0? Советую проверить режимы дисков в hdparm.

sig_wall
( 10.11.09 00:53:11 MSK )
Ответ на: высокий iowait, низкая скорость работы дисков от moskovitter 09.11.09 23:05:25 MSK

высокий iowait, низкая скорость работы дисков

ну тогда надо исключить очевидное. заменить сата-шнурки к примеру

Komintern ★★★★★
( 10.11.09 09:08:22 MSK )
Ответ на: высокий iowait, низкая скорость работы дисков от Komintern 10.11.09 09:08:22 MSK

Re: высокий iowait, низкая скорость работы дисков

Сразу на двух дисках накрылись шнурки и когда менялся один из дисков, шнурок тоже менялся. Не вариант

moskovitter
( 10.11.09 09:40:12 MSK ) автор топика
Ответ на: Re: высокий iowait, низкая скорость работы дисков от moskovitter 10.11.09 09:40:12 MSK

Re: высокий iowait, низкая скорость работы дисков

Скорость работы дисков пропорциональна нагрузке создаваемой httpd. Сейчас вот 8 подключений к виртуалхосту, который на втором диске к примеру, скорость видно что уже ненормальная:

/dev/sdb: Timing buffered disk reads: 58 MB in 3.13 seconds = 18.52 MB/sec

Повторюсь, что на каждом сервере по два диска и грубо говоря на каждом есть директория одного виртуалхоста. На первом сервере начинают тормозить оба диска в зависимости и пропорционально подключениям к виртуалхостам На втором сервере все летает мухой вне зависимости от всего.

moskovitter
( 10.11.09 10:02:44 MSK ) автор топика
Ответ на: Re: высокий iowait, низкая скорость работы дисков от moskovitter 10.11.09 10:02:44 MSK

высокий iowait, низкая скорость работы дисков

что говорит hdparm -I?

Black_Shadow ★★★★★
( 10.11.09 11:52:47 MSK )
Ответ на: высокий iowait, низкая скорость работы дисков от Black_Shadow 10.11.09 11:52:47 MSK

Re: высокий iowait, низкая скорость работы дисков

hdparm для тормозной машины:

[root@www16 ~]# hdparm -I /dev/sdb

ATA device, with non-removable media Model Number: ST3500630AS Serial Number: 6QG14M7J Firmware Revision: 3.AAK Standards: Supported: 7 6 5 4 Likely used: 7 Configuration: Logical max current cylinders 16383 16383 heads 16 16 sectors/track 63 63 — CHS current addressable sectors: 16514064 LBA user addressable sectors: 268435455 LBA48 user addressable sectors: 976773168 device size with M = 1024*1024: 476940 MBytes device size with M = 1000*1000: 500107 MBytes (500 GB) Capabilities: LBA, IORDY(can be disabled) Queue depth: 32 Standby timer values: spec’d by Standard, no device specific minimum R/W multiple sector transfer: Max = 16 Current = 16 Recommended acoustic management value: 254, current value: 0 DMA: mdma0 mdma1 mdma2 udma0 udma1 udma2 udma3 udma4 udma5 *udma6 Cycle time: min=120ns recommended=120ns PIO: pio0 pio1 pio2 pio3 pio4 Cycle time: no flow control=120ns IORDY flow control=120ns Commands/features: Enabled Supported: * SMART feature set Security Mode feature set * Power Management feature set * Write cache * Look-ahead * Host Protected Area feature set * WRITE_BUFFER command * READ_BUFFER command * DOWNLOAD_MICROCODE SET_MAX security extension * 48-bit Address feature set * Device Configuration Overlay feature set * Mandatory FLUSH_CACHE * FLUSH_CACHE_EXT * SMART error logging * SMART self-test * General Purpose Logging feature set * SATA-I signaling speed (1.5Gb/s) * Native Command Queueing (NCQ) * Phy event counters Device-initiated interface power management * Software settings preservation Security: Master password revision code = 65534 supported not enabled not locked frozen not expired: security count not supported: enhanced erase Checksum: correct

[root@fast ~]# hdparm -I /dev/sdb

ATA device, with non-removable media Model Number: ST3500418AS Serial Number: 6VM0DM15 Firmware Revision: CC34 Transport: Serial Standards: Supported: 8 7 6 5 Likely used: 8 Configuration: Logical max current cylinders 16383 16383 heads 16 16 sectors/track 63 63 — CHS current addressable sectors: 16514064 LBA user addressable sectors: 268435455 LBA48 user addressable sectors: 976773168 device size with M = 1024*1024: 476940 MBytes device size with M = 1000*1000: 500107 MBytes (500 GB) Capabilities: LBA, IORDY(can be disabled) Queue depth: 32 Standby timer values: spec’d by Standard, no device specific minimum R/W multiple sector transfer: Max = 16 Current = 16 Recommended acoustic management value: 254, current value: 0 DMA: mdma0 mdma1 mdma2 udma0 udma1 udma2 udma3 udma4 udma5 *udma6 Cycle time: min=120ns recommended=120ns PIO: pio0 pio1 pio2 pio3 pio4 Cycle time: no flow control=120ns IORDY flow control=120ns Commands/features: Enabled Supported: * SMART feature set Security Mode feature set * Power Management feature set * Write cache * Look-ahead * Host Protected Area feature set * WRITE_BUFFER command * READ_BUFFER command * DOWNLOAD_MICROCODE Power-Up In Standby feature set SET_FEATURES required to spinup after power up SET_MAX security extension * Automatic Acoustic Management feature set * 48-bit Address feature set * Device Configuration Overlay feature set * Mandatory FLUSH_CACHE * FLUSH_CACHE_EXT * SMART error logging * SMART self-test * General Purpose Logging feature set * WRITE__FUA_EXT * 64-bit World wide name Write-Read-Verify feature set * WRITE_UNCORRECTABLE command * _DMA_EXT_GPL commands * Segmented DOWNLOAD_MICROCODE * SATA-I signaling speed (1.5Gb/s) * SATA-II signaling speed (3.0Gb/s) * Native Command Queueing (NCQ) * Phy event counters Device-initiated interface power management * Software settings preservation Security: Master password revision code = 65534 supported not enabled not locked frozen not expired: security count supported: enhanced erase 80min for SECURITY ERASE UNIT. 80min for ENHANCED SECURITY ERASE UNIT. Checksum: correct

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *