Last x crash linux

Kdump — диагностика и анализ причин сбоев ядра

Хотя в современных Linux-системах ядро отличается достаточно высоким уровнем стабильности, вероятность серьезных системных ошибок, тем не менее, имеется всегда. Когда происходит неисправимая ошибка, имеет место состояние, называемое паникой ядра (kernel panic): стандартный обработчик выводит на экран информацию, которая должна помочь в устранении неисправности, и входит в бесконечный цикл.

Для диагностики и анализа причин сбоев ядра разработчиками компании RedHat был разработан специализированный инструмент — kdump. Принцип его работы можно кратко описать следующим образом. Создается два ядра: основное и аварийное (именно оно используется для сбора дампа памяти). При загрузке основного ядра под аварийное ядро выделяется определенный размер памяти. При помощи kexec во время паники основного ядра загружается аварийное и собирает дамп.

В этой статье мы подробно расскажем о том, как конфигурировать kdump и анализировать с его помощью системные ошибки. Мы рассмотрим особенности работы с kdump в OC Ubuntu; в других дистрибутивах процедуры настройки и конфигурирования kdump существенно отличаются.

Установка и настройка kdump

Установим kdump с помощью команды

Настройки kdump хранятся в конфигурационном файле /etc/default/kdump-tools

Чтобы активировать kdump, отредактируем этот файл и установим значение параметра USE_KDUMP=1.
Также в конфигурационном файле содержатся следующие параметры:

  • KDUMP_KERNEL — полный путь к аварийному ядру;
  • KDUMP_INITRD — полный путь к initrd аварийного ядра;
  • KDUMP_CORE — указывает, где будет сохранен файл дампа ядра. По умолчанию дамп сохраняется в директории /var/crash (KDUMP_CORE=/var/crash);
  • KDUMP_FAIL_CMD — указывает, какое действие нужно совершить в случае ошибки при сохранении дампа (по умолчанию будет выполнена команда reboot -f);
  • DEBUG_KERNEL — отладочная версия работающего ядра. По умолчанию используются /usr/lib/debug/vmlinux-$. Если значение этого параметра не установлено, утилита makedumpfile создаст только дамп всех страниц памяти;
  • MAKEDUMP_ARGS — содержит дополнительные аргументы, передаваемые утилите makedumpfile. По умолчанию этот параметр имеет значение ‘-c -d 31’, указывающую, что необходимо использовать сжатие и включать в дамп только используемые страницы ядра.

Установив все необходимые параметры, выполним команду update-grub и выберем install the package maintainer’s version.

Затем перезагрузим систему и убедимся в том, что kdump готов к работе:

Обратим особое внимание на параметр crashkernel=384 -:128M. Он означает, что аварийное ядро будет использовать 128 Мб памяти при загрузке. Можно прописать в grub параметр crashkernel = auto: в этом случае память под аварийное ядро будет выделяться автоматически.

Для того, чтобы мы могли анализировать дамп с помощью утилиты crash, нам понадобится также файл vmlinux, содержащий отладочную информацию:

По завершении установки еще раз проверим статус kdump:

Если kdump находится в рабочем состоянии, на консоль будет выведено следующее сообщение:

Тестируем kdump

Вызовем панику ядра при помощи следующих команд:

В результате их выполнения система «зависнет».

После этого в течение нескольких минут будет создан дамп, который будет доступен в директории /var/crash после перезагрузки.

Информацию о сбое ядра можно просмотреть с помощью утилиты crash:

На основе приведенного вывода мы можем заключить, что системному сбою предшествовало событие «Oops: 0002 [#1] SMP», произошедшее на CPU2 при выполнении команды tee.
Утилита crash обладает также широким спектром возможностей для диагностики причин краха ядра. Рассмотрим их более подробно.

Диагностика причин сбоя с помощью утилиты crash

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

В утилите crash имеется свой набор команд:

Для каждой этой команды можно вызвать краткий мануал, например:

Все команды мы описывать не будем (с детальной информацией можно ознакомиться в официальном руководстве пользователя от компании RedHat), а расскажем лишь о наиболее важных из них.

Читайте также:  Windows link file folder

В первую очередь следует обратить внимание на команду bt (аббревиатура от backtrace — обратная трассировка). С ее помощью можно посмотреть детальную информацию о содержании памяти ядра (подробности и примеры использования см. здесь). Однако во многих случаях для определения причины системного сбоя бывает вполне достаточно команды log, выводящее на экран содержимое буфера сообщений ядра в хронологическом порядке.

Приведем фрагмент ее вывода:

В одной из строк вывода будет указано событие, вызвавшее системную ошибку:

С помощью команды ps можно вывести на экран список процессов, которые были запущены на момент сбоя:

Для просмотра информации об использовании виртуальной памяти используется команда vm:

Команда swap выведет на консоль информацию об использовании области подкачки:

Информацию о прерываниях CPU можно просмотреть с помощью команды irq:

Вывести на консоль список файлов, открытых на момент сбоя, можно с помощью команды files:

Наконец, получить в сжатом виде информацию об общем состоянии системы можно с помощью команды sys:

Заключение

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

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

Источник

Kernel Crash Dump

Introduction

A Kernel Crash Dump refers to a portion of the contents of volatile memory (RAM) that is copied to disk whenever the execution of the kernel is disrupted. The following events can cause a kernel disruption :

Non Maskable Interrupts (NMI)

Machine Check Exceptions (MCE)

For some of those events (panic, NMI) the kernel will react automatically and trigger the crash dump mechanism through kexec. In other situations a manual intervention is required in order to capture the memory. Whenever one of the above events occurs, it is important to find out the root cause in order to prevent it from happening again. The cause can be determined by inspecting the copied memory contents.

Kernel Crash Dump Mechanism

When a kernel panic occurs, the kernel relies on the kexec mechanism to quickly reboot a new instance of the kernel in a pre-reserved section of memory that had been allocated when the system booted (see below). This permits the existing memory area to remain untouched in order to safely copy its contents to storage.

Installation

The kernel crash dump utility is installed with the following command:

Starting with 16.04, the kernel crash dump mechanism is enabled by default. During the installation, you will be prompted with the following dialogs.

Select Yes to hook up kexec-tools for all reboots.

Yes should be selected here as well, to enable kdump-tools .

If you ever need to manually enable the functionality, you can use the dpkg-reconfigure kexec-tools and dpkg-reconfigure kdump-tools commands and answer Yes to the questions. You can also edit /etc/default/kexec and set parameters directly:

As well, edit /etc/default/kdump-tools to enable kdump by including the following line:

If a reboot has not been done since installation of the linux-crashdump package, a reboot will be required in order to activate the crashkernel= boot parameter. Upon reboot, kdump-tools will be enabled and active.

If you enable kdump-tools after a reboot, you will only need to issue the kdump-config load command to activate the kdump mechanism.

You can view the current status of kdump via the command kdump-config show . This will display something like this:

This tells us that we will find core dumps in /var/crash.

Configuration

In addition to local dump, it is now possible to use the remote dump functionality to send the kernel crash dump to a remote server, using either the SSH or NFS protocols.

Local Kernel Crash Dumps

Local dumps are configured automatically and will remain in use unless a remote protocol is chosen. Many configuration options exist and are thoroughly documented in the /etc/default/kdump-tools file.

Читайте также:  Canon 1100d mac os

Remote Kernel Crash Dumps using the SSH protocol

To enable remote dumps using the SSH protocol, the /etc/default/kdump-tools must be modified in the following manner :

The only mandatory variable to define is SSH. It must contain the username and hostname of the remote server using the format @.

SSH_KEY may be used to provide an existing private key to be used. Otherwise, the kdump-config propagate command will create a new keypair. The HOSTTAG variable may be used to use the hostname of the system as a prefix to the remote directory to be created instead of the IP address.

The following example shows how kdump-config propagate is used to create and propagate a new keypair to the remote server :

The password of the account used on the remote server will be required in order to successfully send the public key to the server

The kdump-config show command can be used to confirm that kdump is correctly configured to use the SSH protocol :

Remote Kernel Crash Dumps using the NFS protocol

To enable remote dumps using the NFS protocol, the /etc/default/kdump-tools must be modified in the following manner :

As with the SSH protocol, the HOSTTAG variable can be used to replace the IP address by the hostname as the prefix of the remote directory.

The kdump-config show command can be used to confirm that kdump is correctly configured to use the NFS protocol :

Verification

To confirm that the kernel dump mechanism is enabled, there are a few things to verify. First, confirm that the crashkernel boot parameter is present (note: The following line has been split into two to fit the format of this document:

The crashkernel parameter has the following syntax:

So for the crashkernel parameter found in /proc/cmdline we would have :

The above value means:

if the RAM is smaller than 384M, then don’t reserve anything (this is the “rescue” case)

if the RAM size is between 386M and 2G (exclusive), then reserve 64M

if the RAM size is larger than 2G, then reserve 128M

Second, verify that the kernel has reserved the requested memory area for the kdump kernel by doing:

Finally, as seen previously, the kdump-config show command displays the current status of the kdump-tools configuration :

Testing the Crash Dump Mechanism

Testing the Crash Dump Mechanism will cause a system reboot. In certain situations, this can cause data loss if the system is under heavy load. If you want to test the mechanism, make sure that the system is idle or under very light load.

Verify that the SysRQ mechanism is enabled by looking at the value of the /proc/sys/kernel/sysrq kernel parameter :

If a value of 0 is returned the dump and then reboot feature is disabled. A value greater than 1 indicates that a sub-set of sysrq features is enabled. See /etc/sysctl.d/10-magic-sysrq.conf for a detailed description of the options and the default value. Enable dump then reboot testing with the following command :

Once this is done, you must become root, as just using sudo will not be sufficient. As the root user, you will have to issue the command echo c > /proc/sysrq-trigger . If you are using a network connection, you will lose contact with the system. This is why it is better to do the test while being connected to the system console. This has the advantage of making the kernel dump process visible.

A typical test output should look like the following :

The rest of the output is truncated, but you should see the system rebooting and somewhere in the log, you will see the following line :

Once completed, the system will reboot to its normal operational mode. You will then find the Kernel Crash Dump file, and related subdirectories, in the /var/crash directory :

If the dump does not work due to OOM (Out Of Memory) error, then try increasing the amount of reserved memory by editing /etc/default/grub.d/kdump-tools.cfg . For example, to reserve 512 megabytes :

Читайте также:  Sonic games для windows

run sudo update-grub and then reboot afterwards, and then test again.

Resources

Kernel Crash Dump is a vast topic that requires good knowledge of the linux kernel. You can find more information on the topic here :

Analyzing Linux Kernel Crash (Based on Fedora, it still gives a good walkthrough of kernel dump analysis)

Источник

How can I track the cause of random reboots?

A Thinkpad X220 (Core-i5, SandyBridge, Intel GMA) running Precise 64-bit has rebooted hard twice in the last four days. I was doing nothing more than writing an email. No warning. It just went black, and the next thing I saw was the Lenovo boot screen.

Where should I look to find the cause? I fear that this immediate reboot does not leave time for logs to be written.

4 Answers 4

Check /proc/sys/kernel/panic ; if its value is 1 then the server will immediately reboot on panic. Buggy drivers can cause a kernel panic.

If it’s not a panic check last issue of reboot, maybe overheating is the issue.

Commands

  1. dmesg — May not show items from before last boot, but very useful if the system is still up

Files

  1. /var/log/syslog — System wide logger, use tail /var/log/syslog or less /var/log/syslog
  2. /var/log/kern.log — Kernel log, same as above
  3. /var/log/*

TL;DR: @insider’s answer, along with the comments by @Antonios Hadjigeorgalis led me to find that I had

I was experiencing sudden reboots, mostly soon after turning my laptop on in the morning. I’m running Ubuntu 18.04. Running last reboot showed that the kernel version was usually newer after the sudden reboots:

Looking into /etc/apt/apt.conf.d/50unattended-upgrades , I saw that «Unattended-Upgrade::Automatic-Reboot» was commented out, and its default is supposedly false. I then ran the following:

And there was my problem — Unattended-Upgrade::Automatic-Reboot «true»; in /etc/apt/apt.conf.d/99custom-unattended-upgrades .

Application crashes have crash files in /var/crash/ ; I’d also explore normal system logs which are your best bet. If the hardware shutdown you won’t see anything in the systemd & message logs (a HUGE clue!!). If Ubuntu was aware of shutdown you’ll see that too as you’ll see reasons for shutdown. (If no details are found you’ll need to check machine logs; ie. HOST OS if VM or hardware logs if on metal)

To look at app crashes on this box

Starting with application crashes is easy, so I’d look there first, however I can’t really think of why a application crash could cause a reboot or shutdown; so I’d not expect to see anything meaningful there (if it’s useful; it’ll be after system logs).

To view system messages (for current session) you can use dmesg . Because it’ll show the current session only, you won’t see a reason for the last shutdown (that was last session), but after an unclean shutdown I’d expect to see results of a fsck (because of unplanned shutdown).

The best clues however are in systemd journals, or journalctl . This is where I’d really look for clues on last shutdown, ie. it’s here where I’d expect to see the lack of normal shutdown messages which means it’s a clue of hardware shutdown (eg. cpu shutoff because of extreme heat threshold; a pin gets grounded with OS having no clue so messages just stop! and next message is normal booting of next session; such messages will be found in hardware logs assuming an enterprise server; consumer grade usually don’t keep hardware logs).

Sometimes you can see clues of overheating in logs anyway; bad if the PSU has issues (PWR_GOOD drops) nothing will be found as CPU wasn’t even aware of shutdown; I suspect hardware logs may miss this type of shutdown too (but lack of entries is still a clue!)

To further narrow down where to look though, will depend on what type of server, what is running on it, and details that haven’t been provided.

Источник

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