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

Kernel panic что это

  • автор:

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 (на телефонах

Примечания

  1. ↑Unix and Multics
  2. ↑Причины для Kernel panic в Mac OS X
  3. ↑Исходный код prf.c UNIX V6
  4. ↑TIP Kernel Panic Reboot
  5. ↑OpenBSD SYSCTL.CONF man page
  6. ↑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.

  1. 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
  2. You can use panic parameter which reboots kernel after n seconds. You can instruct GRUB to switch to fallback kernel in such case
  3. 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:

  1. It detects a software error in the kernel code or stack
  2. When there is a run-time condition such as out-of-memory with no killable processes
  3. 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.

What is kernel panic?

What is kernel panic?
When the kernel can’t load properly or «freaks out» and fails to boot properly or crashes(see edit credit at the bottom).

Why it occurs?
Hosed updates, failing hardware, unsupported hardware, failed or missing drive or partition (see edit credit at the bottom)

How can I understand kernel panic occurred?
Watch boot prompts(turn off quiet kernel parameter) OR your machine fails to boot

What effect it has on system?
Failure to boot or system crash

Does it only occur in Linux?
No, all unix-like operating systems can have kernel panics. It’s the equivalent of a Windows Blue Screen of Death

How can I prevent it?
It normally doesn’t happen. Test updates and troubleshoot the problem. Use stable instead of development branches.

Additional note: Kernel panic and system failure/shutdown can be directly responsible for protecting your computer from physical damage. Examples include halting before extreme overheating or disk corruption. See edit credits at the bottom for direct quote.

edits

Per B. Roland Missing or corrupted disks or volumes can cause this as well.
(Good point and I overlooked it)

Per Kees Kernel panic can also occur while running.
note: Can happen when a function fails sort of gracefully inside the kernel, but most often happens during module or kernel loading(which is usually during boot). I thought I touched on it at «during boot or system crash», but I see how my answer to (1) stated it only occurs during boot.

Per rafalcieslak direct quote — ‘There is one very important thing that must be added: The main point in the whole kernel panic is to protect your computer. The kernel freezes not only because it failed to do something, but also in order to prevent your computer from f.e. overheating, hard drives corruption, and any other hardware problems, that may occur, if some incorrect orders are executed, of a module (for example a module responsible for controlling the fan) failed to load, etc. This is why the kernel prefers to freeze, than to overcome the problem.’

A kernel panic happens when the kernel detects an error from which it can’t recover. A function named panic() to handle this situation (often by dumping some debug info and/or rebooting the system) was first introduced in one of the very early UNIX versions, so that’s where the name comes from (and it’s still called that in most UNIX-like operating systems, including Mac OS X).

The famous Blue Screen Of Death (officially called a Fatal system error, as in VMS/OpenVMS) in Microsoft’s NT kernel is also a form of «kernel panic».

A linux kernel error from which the kernel can (partially or temporarily) recover is called a kernel oops (you might see those in dmesg output sometimes).

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

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