Kernel Panic on Linux and how to fix it
In basic terms a kernel panic is a situation when kernel can’t load properly and fails to boot properly or crashes. When the kernel detects an error from which it cannot recover itself. This happens rarely but it is majorly caused due to hosed updates or failing hardware or missing drive or partitions results in panic or voluntary halt to system activity.
Why does it occurs?
A panic may occur as a result of hardware failure or a software bug in the Operating System. Primarily, two things happen when kernel is unable to proceed : the Software runs out of resources and hardware does something unexpectedly or does not do anything. This might happen due to hosed updates, failing hardware, failed or missing drive or partitions. It also occurs in order to prevent your computer from data corruption, risking security breaches as system is in unstable state. So OS stops to prevent damage and facilitates diagnosis of the error and, in usual cases, restart.
How can I understand kernel panic occurred?
Read the boot prompts or turnoff quiet kernel parameter or your machine fails to boot.
What is the effect it has on system?
It might end up crashing your system or failure to boot.
How can I prevent it?
It normally doesn’t happen. But it so, test updates and troubleshoot the problem. Use stable instead of development branches.
For Linux
If kernel panic occurs because of updates to Linux-image-generic then :
Reboot to last working kernel and remove the latest unstable Linux image generic package.
Few days back I faced kernel panic in my laptop and got confused that why it is happening. I tried re-starting my laptop again and again. Then, I searched about it over the internet and understood the problem and here is how I solved the issue.
Steps to follow :
- 1 Press shift between UEFI/BIOS and login-screen to enter GRUB.
- In GRUB select Advanced options for Ubuntu and select Ubuntu, with Linux 4.13.0-xxx-generic where(xxx < 108)
- Login to the system and remove the latest generic image and install the stable package instead.
or else you can type sudo apt install linux-image-4.13.0-xxx-generic where(xxx < 108)
Паника ядра
Kernel panic (англ. букв.: паника ядра) — сообщение о критической ошибке ядра операционной системы, после которой операционная система не может продолжать дальнейшую работу.
Обычно этот термин применяется в среде операционных систем типа Kernel panic: … » и именем функции ядра panic() из оригинальной ОС Linux возникновению паники ядра зачастую предшествует состояние под названием oops. В ряде случаев oops может приводить к такому же неработоспобному состоянию системы, как и паника ядра.
Содержание
История
Сообщение Kernel panic было введено в ранних версиях операционной системы от главного конкурента на то время, Денисом Ритчи [1] :
Я сказал Деннису, что примерно половина кода, который я написал для Multics, был кодом обработки ошибок. Он ответил: «Мы всё это отбросили. Если произошла ошибка, у нас есть процедура под названием panic и если она вызвана, компьютер зависает и вы кричите: „Эй, перезапустите его!“»
I remarked to Dennis that easily half the code I was writing in Multics was error recovery code. He said, «We left all that stuff out. If there’s an error, we have this routine called panic, and when it is called, the machine crashes, and you holler down the hall, ‘Hey, reboot it.’
Изначальная функция panic() принципиально не менялась от UNIX V5 до базирующихся на бесконечный пустой цикл. Позже, в процессе развития UNIX, функция panic() также была доработана и стала выводить на терминал разнообразную информацию, необходимую для отладки.
Подобный принцип обработки критических ошибок был перенят большинством более поздних операционных систем, таких как Mac OS [2] или Microsoft Windows.
Причины для Kernel panic
В большинстве случаев причиной для Kernel panic является критическая аппаратная ошибка (отказ оперативной памяти, ошибка процессора или другого критически важного устройства) или ошибка в самом ядре операционной системы, например попытка обращения к ошибочному или запрещённому адресу в памяти. Также причиной для Kernel panic могут быть ошибки в драйверах периферийных устройств или ошибки в файловой системе.
Ошибки пользовательских программ в современных операционных системах не приводят к Kernel panic и должны корректно обрабатываться ядром.
Исходный код функции panic()
Исходный код функции panic() в [3] :
Обработка Kernel panic
В нормальном случае при возникновении Kernel panic происходит остановка работы операционной системы с выдачей сообщений об ошибках на экран, после чего система ожидает выключения компьютера или перезагрузки. Однако, такая обработка этого события неприемлема тогда, когда простой компьютера крайне нежелателен или человека нет рядом (например на удалённых серверах или в нерабочее время).
В современных операционных системах, таких как GNU/Linux, Solaris, существует возможность изменить стандартное поведение функции panic() и производить перезагрузку компьютера автоматически. В GNU/Linux данная настройка осуществляется при помощи
Чтобы изменения действовали в GNU/Linux и после перезагрузки, необходимо добавить в файл /etc/sysctl.conf строку:
В обоих примерах «5» — количество секунд, после которых произойдёт перезагрузка. При установке отрицательного или равного 0 значения этого параметра, автоматической перезагрузки не произойдёт. [4]
В Solaris автоматическая перезагрузка после Kernel panic является стандартным поведением системы. [6]
Перезагрузка после Kernel panic имеет и очень серьёзный недостаток, особенно если это изменение не пропадает после первой перезагрузки. В случае, если перезагрузка не устраняет ту ошибку, которая вызывает Kernel panic, система будет останавливаться и перезапускаться вновь и вновь, что может привести к аппаратным ошибкам или потерям данных.
Для изучения причины паники ядра Linux может пригодится файл Windows XP при возниковении ошибки компьютер перезагружается автоматически. Это поведение системы управляется через Панель управления Windows. Если ошибка происходит при загурзке ОС, изменить поведение системы можно через меню кнопки F8.
Kernel panic в различных операционных системах

Изначально сообщение о Kernel panic ограничивалось коротким текстом о необходимости перезагрузки системы. В современных системах обычно выдается больше дополнительной информации.
-
и большинство других отладки и поиска причин этой ошибки. Этот механизм носит название Linux oops.
- В Mac OS X это сообщение было упрощено и сообщает лишь о необходимости перезапустить компьютер. Среди пользователей оно получило название «The Gray Screen of Panic and Disarray».
В то время как термин Kernel panic употребляется в основном для операционных системах обработка критических ошибок методом остановки системы получила другие названия:
- В OS/2, Windows 3.x: Black Screen of Death (англ.)
- В современных версиях Windows: Blue Screen of Death
- В старых компьютерах
- На компьютерах Guru Meditation
- В PDA работающих под управлением Windows Mobile и Palmtop, Pocket PC, SmartPhone): White Screen of Death (англ.)
- На PSP это надпись на 10 языках: «Данные конфигурации повреждены. Нажмите O (кружок) для восстановления стандартной конфигурации.»
- В Synerji (на телефонах
Примечания
- ↑Unix and Multics
- ↑Причины для Kernel panic в Mac OS X
- ↑Исходный код prf.c UNIX V6
- ↑TIP Kernel Panic Reboot
- ↑OpenBSD SYSCTL.CONF man page
- ↑Device Driver Testing Tips (Solaris)
См. также
Ссылки
- Примеры исходного кода функции panic() в Darwin/Mac OS X, Minix и Linux
Wikimedia Foundation . 2010 .
Полезное
Смотреть что такое «Паника ядра» в других словарях:
The Gray Screen of Panic and Disarray — Kernel panic (англ. букв.: паника ядра) сообщение о критической ошибке ядра операционной системы, после которой операционная система не может продолжать дальнейшую работу. Обычно этот термин применяется в среде операционных систем типа Kernel… … Википедия
Kernel panic — Linux 2.6 не может смонтировать корневую файловую систему. Kernel panic (англ.: тревога, сбой в ядре) сообщение о критической о … Википедия
Ядерный взрыв — … Википедия
Падение Константинополя (1453) — У этого термина существуют и другие значения, см. Падение Константинополя (значения). Падение Константинополя Турецко византийские войны … Википедия
Дьявол из Джерси — Об одноимённом эпизоде «Секретных материалов» см. Дьявол из Джерси (Секретные материалы) … Википедия
Дьявол из Джерси (мифическое существо) — Рисунок дьявола из Джерси в газете Philadelphia Post 1909 года. Дьявол из Джерси легендарное существо (возможно, криптид), якобы живущее в степях Pine Barrens на юге американского штата Нью Джерси. Легенда о существе оказала огромное… … Википедия
Страх — У этого термина существуют и другие значения, см. Страх (значения). В Викисловаре есть статья «страх» … Википедия
Кокаин — Кокаин … Википедия
Банковская система — (Banking System) Банковская система это совокупность действующих в стране банков, кредитных учреждений и отдельных экономических организаций, которые действуют по единым правилам денежно кредитной политики страны Определение банковской системы,… … Энциклопедия инвестора
НАПОЛЕОН I — Французский император из династии Бонапартов, правивший в 1804 1814,1815 гг. Король Италии в 1805 1814 гг. Сын Карло Буонапарте и Летиции Рамолино. Ж.: 1) с 1796 г. Жозефина, урожденная Ташер де ла Пажери, вдова виконта Александра Богарнэ (род.… … Все монархи мира
What is a "kernel panic"?
What does it mean when your computer has a «kernel panic»?
Does it equate to the windows BsoD?
Also, what methods, tips, tricks are available to the user when a kernel panic strikes?
3 Answers 3
Kernel panic is the same as BSOD and is non-rescuable IIRC. However smaller failure is OOPS which denotes some error in kernel.
- You can use kexec which switches to new kernel on panic (you can threat it as fast reboot) — possibly getting meaningful dump of system to debug the problem
- You can use panic parameter which reboots kernel after n seconds. You can instruct GRUB to switch to fallback kernel in such case
- Use Magic SysRQ keys to print stack traces etc.
A Linux kernel panic is a subroutine call that the kernel executes when the kernel logic determines that a condition exists that makes continued execution of the normal logic impossible or irresponsible.
The kernel can call a panic when:
- It detects a software error in the kernel code or stack
- When there is a run-time condition such as out-of-memory with no killable processes
- A CPU exception during privileged mode execution results in an oops condition
There are about 950 distinct conditions where a panic is called in the 3.X kernels. The panic subroutine first prints the kernel stack dump and CPU registers to the console. Then, if a crash kexec kernel has been configured, it boots the kexec kernel. Otherwise the panic routine busts all spinlocks and performs an emergency restart.
An oops is a subroutine called from a CPU exception handler for a CPU exception that occurs while executing in privileged (i.e kernel) mode. The exception can occur as a result of an error in kernel code, or because of a hardware failure, or as the result of an external condition that causes a specific exception. The handler for the exception prints a kernel log with CPU registers and modules list. Unlike panic calls, the kernel logic itself never calls an oops outside the context of CPU exception handlers.
If the kernel is configured for kexec, then an oops will result in the kexec kernel being booted. Otherwise, if the exception occurs while executing an interrupt handler, then the oops results in a kernel panic call. Otherwise, if the kernel is is configured with “panic on oops”, then the oops will result in a panic call. Otherwise the the kernel exits the exception handler and resumes execution. When the kernel exits the exception handler and resumes execution, the integrity of the kernel is suspect.
CPU exception handlers are architecture-specific. They are usually implemented in arch/*/kernel/traps.c, and set in the architecture-specific kernel entry code that sets up the interrupt table. See for example arch/powerpc/kernel/traps.c and arch/powerpc/kernel/head_fsl_booke.S .
Both kernel panic and oops conditions can be configured to call a kmsg_dump routine that you can use to save crash debugging information to RAM, or to flash memory unless the oops occurred in interrupt context, in which case the “kmsg_dump” routine can only be used to save to RAM, not to MTD. When saving to RAM, it is your responsibility to a) ensure that the RAM area used is not overwritten during kexec boot or emergency restart boot, and b) to harvest the memory area from the kexec kernel or from the boot loader logic.
Kernel Panic
Unrecoverable system errors are called kernel panics.
Contents
Overview
![]()

![]()

![]()

![]()

![]()

History
Windows used to be very very unstable (almost every pre-NT kernel versions, and early NT versions). When they crashed, they displayed an error message with white text and blue background. This happened so often, that it made to the pop culture, dubbed «Blue Screen of Death», hence the acronym «BSOD».
Despite of the name’s origin, BSOD is not unique to Windows, all systems has this feature, but they are usually black instead of blue.
Purpose
The main purpose of a kernel panic screen is to inform the user that an unrecoverable error happened, and they have to reset the computer to continue. Quite often the crash screen contains low-level information for developers to help debugging.
Such low-level information often includes a textual error message, stack trace and register dumps.
There are at least a few OSes which go a step further, and instead of displaying the debug information provide a built-in debugger which can be used interactively if system crash happens. For example Amiga could be debugged remotely using serial connection, and some modern systems start gdb-server. In general systems that has some sort of debugging capability tend to display less information on the crash screen.
For big money corp OSes (running on rack servers and mainframes and alike) it is very common not to display any information, except for a code. The maintainers are supposed to pay insanely huge amounts of money for courses where they get a printed documentation which lists those codes and how to workaround each. Luckily those «big» OSes are well written and very rarely crash.
Atari ST is an example of a minimalistic screen: it displayed 2 to 9 bombs depending on the error. It was a very limited error code system.
Funky side
Because crash screen by its nature is a sad to see, developers started to put little things on screen to cheer the users up. One of the earliest examples is Amiga’s «Guru Meditation», suggesting that the user will need a computer guru to solve the problem. Later they renamed it to «Grim Reaper». Undeniably funnier than a simple «System Crashed».
The reason why Microsoft picked the blue background is because according to shrinks, blue makes people calm.
For OSes with the console metaphor funny ASCII arts are also very popular, specially among hobby OS developers. This is not uncommon to mainstream either, although most just prints developer debug, some BSDs draw ASCII arts too.
Implementation
To implement a kernel panic in your kernel, you’ll have to write a special function. This function must be dependency-free, and must not rely on other parts of your kernel. It must be self-contained, so that it can display the screen regardless which parts of your OS failed. This function is commonly called «kpanic», but you can give any name to it you’d like.
On legacy x86 computers implementing kernel panics is simple, as you can write characters into the video memory at 0xB8000 directly. For a modern PC implementing kernel panics is a little bit more difficult, as the framebuffer has no fixed address, and you have to include a font renderer and your own font too.
For an example, an implementation could load a self-contained kpanic() routine to a fixed address below the 1Meg mark. This module would have a predefined header at the beginning, holding a pointer to the initialization routine, as well as information about the current screen mode. If and when your kernel panics, all it has to do is retrieve this header from this fixed location, grab the initialization address, and jump to it.
A few notes to consider:
Explicit Invocation
You can call this kpanic from your kernel when a specific error condition met. For example during boot, if you figure there’s not enough RAM, or the CPU lacks a feature that your kernel depends on, you failed load an important system file etc.
Implicit Invocation
Then it is also very common to start with a single exception handler that does nothing else than calling kpanic. You set up this in the IDT for all exceptions, and as your kernel development progresses, you replace the handlers one-by-one with their final implementations. This way exceptions that are not handled properly by your kernel will always trigger a BSOD.
Examples
Windows NT
On Windows NT kernel panics are technically called «bug checks». Prior to Windows 8 the bug check screen displayed context info, currently it displays only a bug check code and some graphics. The bug check routine is provided by the kernel and it uses many HAL and boot video driver functions, to reset the current display device, emulate the bios to set up a VGA mode, other services are provided by the kernel and the debugger modules, to output to the debugger, to freeze the remaining processors and mask off and disable any interrupts on the current processor so the system would stop running.
MacOSX
Note the complete lack of any technical information, not even an errorcode shown. It worth noting that MacOSX also has a console-only kernel panic, which looks like BSD’s. (However MacOSX saves a memory dump to disk and starts a gdb-server to allow a remote debugger to be connected on crash, so there’s really no need to print any details on screen.)
FreeBSD
All about minimal required information, note the stack trace. I believe this is optimal amount of information.
Linux
As much information as possible, important details often lost in the noise. Includes register dumps and stack trace, and requires a screen pager. Totally frightening to average users, no clear instructions for non-experts what to do.
Hobby OSes
An example of a built-in debugger on a crash screen would be OS/Z an operating system developed by one of the OSDev’s forum members. For further examples, the forum topic When your OS goes crazy has many examples of funny ASCII arts.
Other
Xscreensaver’s BSOD module displays mockups of many operating systems’ kernel panics along with a few other situations. The first half of this video shows a few of them.