Linux Magic System Request Key Hacks

Documentation for sysrq.c

What is the magic SysRq key?

It is a ‘magical’ key combo you can hit which the kernel will respond toregardless of whatever else it is doing, unless it is completely locked up.

How do I enable the magic SysRq key?

You need to say “yes” to ‘Magic SysRq key (CONFIG_MAGIC_SYSRQ)’ whenconfiguring the kernel. When running a kernel with SysRq compiled in,/proc/sys/kernel/sysrq controls the functions allowed to be invoked viathe SysRq key. The default value in this file is set by theCONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE config symbol, which itself defaultsto 1. Here is the list of possible values in /proc/sys/kernel/sysrq:

  • 0 - disable sysrq completely

  • 1 - enable all functions of sysrq

  • >1 - bitmask of allowed sysrq functions (see below for detailed functiondescription):

      2 =   0x2 - enable control of console logging level  4 =   0x4 - enable control of keyboard (SAK, unraw)  8 =   0x8 - enable debugging dumps of processes etc. 16 =  0x10 - enable sync command 32 =  0x20 - enable remount read-only 64 =  0x40 - enable signalling of processes (term, kill, oom-kill)128 =  0x80 - allow reboot/poweroff256 = 0x100 - allow nicing of all RT tasks

You can set the value in the file by the following command:

echo "number" >/proc/sys/kernel/sysrq

The number may be written here either as decimal or as hexadecimalwith the 0x prefix. CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE must always bewritten in hexadecimal.

Note that the value of/proc/sys/kernel/sysrq influences only the invocationvia a keyboard. Invocation of any operation via/proc/sysrq-trigger isalways allowed (by a user with admin privileges).

How do I use the magic SysRq key?

On x86

You press the key comboALT-SysRq-<command key>.

Note

Somekeyboards may not have a key labeled ‘SysRq’. The ‘SysRq’ key isalso known as the ‘Print Screen’ key. Also some keyboards cannothandle so many keys being pressed at the same time, so you mighthave better luck with pressAlt, pressSysRq,releaseSysRq, press<command key>, release everything.

On SPARC
You pressALT-STOP-<command key>, I believe.
On the serial console (PC style standard serial ports only)
You send aBREAK, then within 5 seconds a command key. SendingBREAK twice is interpreted as a normal BREAK.
On PowerPC
PressALT - Print Screen (orF13) -<command key>.Print Screen (orF13) -<command key> may suffice.
On other
If you know of the key combos for other architectures, pleaselet me know so I can add them to this section.
On all

Write a character to /proc/sysrq-trigger. e.g.:

echo t > /proc/sysrq-trigger

What are the ‘command’ keys?

CommandFunction
bWill immediately reboot the system without syncing or unmountingyour disks.
cWill perform a system crash by a NULL pointer dereference.A crashdump will be taken if configured.
dShows all locks that are held.
eSend a SIGTERM to all processes, except for init.
fWill call the oom killer to kill a memory hog process, but do notpanic if nothing can be killed.
gUsed by kgdb (kernel debugger)
hWill display help (actually any other key than those listedhere will display help. buth is easy to remember :-)
iSend a SIGKILL to all processes, except for init.
jForcibly “Just thaw it” - filesystems frozen by the FIFREEZE ioctl.
kSecure Access Key (SAK) Kills all programs on the current virtualconsole. NOTE: See important comments below in SAK section.
lShows a stack backtrace for all active CPUs.
mWill dump current memory info to your console.
nUsed to make RT tasks nice-able
oWill shut your system off (if configured and supported).
pWill dump the current registers and flags to your console.
qWill dump per CPU lists of all armed hrtimers (but NOT regulartimer_list timers) and detailed information about allclockevent devices.
rTurns off keyboard raw mode and sets it to XLATE.
sWill attempt to sync all mounted filesystems.
tWill dump a list of current tasks and their information to yourconsole.
uWill attempt to remount all mounted filesystems read-only.
vForcefully restores framebuffer console
vCauses ETM buffer dump [ARM-specific]
wDumps tasks that are in uninterruptable (blocked) state.
xUsed by xmon interface on ppc/powerpc platforms.Show global PMU Registers on sparc64.Dump all TLB entries on MIPS.
yShow global CPU Registers [SPARC-64 specific]
zDump the ftrace buffer
0-9Sets the console log level, controlling which kernel messageswill be printed to your console. (0, for example would makeit so that only emergency messages like PANICs or OOPSes wouldmake it to your console.)

Okay, so what can I use them for?

Well, unraw(r) is very handy when your X server or a svgalib program crashes.

sak(k) (Secure Access Key) is useful when you want to be sure there is notrojan program running at console which could grab your passwordwhen you would try to login. It will kill all programs on given console,thus letting you make sure that the login prompt you see is actuallythe one from init, not some trojan program.

Important

In its true form it is not a true SAK like the one in ac2 compliant system, and it should not be mistaken assuch.

It seems others find it useful as (System Attention Key) which isuseful when you want to exit a program that will not let you switch consoles.(For example, X or a svgalib program.)

reboot(b) is good when you’re unable to shut down, it is an equivalentof pressing the “reset” button.

crash(c) can be used to manually trigger a crashdump when the system is hung.Note that this just triggers a crash if there is no dump mechanism available.

sync(s) is handy before yanking removable medium or after using a rescueshell that provides no graceful shutdown – it will ensure your data issafely written to the disk. Note that the sync hasn’t taken place until you seethe “OK” and “Done” appear on the screen.

umount(u) can be used to mark filesystems as properly unmounted. From therunning system’s point of view, they will be remounted read-only. The remountisn’t complete until you see the “OK” and “Done” message appear on the screen.

The loglevels0-9 are useful when your console is being flooded withkernel messages you do not want to see. Selecting0 will prevent all butthe most urgent kernel messages from reaching your console. (They willstill be logged if syslogd/klogd are alive, though.)

term(e) andkill(i) are useful if you have some sort of runaway processyou are unable to kill any other way, especially if it’s spawning otherprocesses.

“just thawit(j)” is useful if your system becomes unresponsive due to afrozen (probably root) filesystem via the FIFREEZE ioctl.

Sometimes SysRq seems to get ‘stuck’ after using it, what can I do?

That happens to me, also. I’ve found that tapping shift, alt, and controlon both sides of the keyboard, and hitting an invalid sysrq sequence againwill fix the problem. (i.e., something likealt-sysrq-z). Switching toanother virtual console (ALT+Fn) and then back again should also help.

I hit SysRq, but nothing seems to happen, what’s wrong?

There are some keyboards that produce a different keycode for SysRq than thepre-defined value of 99(seeKEY_SYSRQ ininclude/uapi/linux/input-event-codes.h), orwhich don’t have a SysRq key at all. In these cases, runshowkey-s to findan appropriate scancode sequence, and usesetkeycodes<sequence>99 to mapthis sequence to the usual SysRq code (e.g.,setkeycodese05b99). It’sprobably best to put this command in a boot script. Oh, and by the way, youexitshowkey by not typing anything for ten seconds.

I want to add SysRQ key events to a module, how does it work?

In order to register a basic function with the table, you must first includethe headerinclude/linux/sysrq.h, this will define everything else you need.Next, you must create asysrq_key_op struct, and populate it with A) the keyhandler function you will use, B) a help_msg string, that will print when SysRQprints help, and C) an action_msg string, that will print right before yourhandler is called. Your handler must conform to the prototype in ‘sysrq.h’.

After thesysrq_key_op is created, you can call the kernel functionregister_sysrq_key(intkey,conststructsysrq_key_op*op_p); this willregister the operation pointed to byop_p at table key ‘key’,if that slot in the table is blank. At module unload time, you must callthe functionunregister_sysrq_key(intkey,conststructsysrq_key_op*op_p),which will remove the key op pointed to by ‘op_p’ from the key ‘key’, if andonly if it is currently registered in that slot. This is in case the slot hasbeen overwritten since you registered it.

The Magic SysRQ system works by registering key operations against a key oplookup table, which is defined in ‘drivers/tty/sysrq.c’. This key table hasa number of operations registered into it at compile time, but is mutable,and 2 functions are exported for interface to it:

register_sysrq_key and unregister_sysrq_key.

Of course, never ever leave an invalid pointer in the table. I.e., whenyour module that called register_sysrq_key() exits, it must callunregister_sysrq_key() to clean up the sysrq key table entry that it used.Null pointers in the table are always safe. :)

If for some reason you feel the need to call the handle_sysrq function fromwithin a function called by handle_sysrq, you must be aware that you are ina lock (you are also in an interrupt handler, which means don’t sleep!), soyou must call__handle_sysrq_nolock instead.

When I hit a SysRq key combination only the header appears on the console?

Sysrq output is subject to the same console loglevel control as allother console output. This means that if the kernel was booted ‘quiet’as is common on distro kernels the output may not appear on the actualconsole, even though it will appear in the dmesg buffer, and be accessiblevia the dmesg command and to the consumers of/proc/kmsg. As a specificexception the header line from the sysrq command is passed to all consoleconsumers as if the current loglevel was maximum. If only the headeris emitted it is almost certain that the kernel loglevel is too low.Should you require the output on the console channel then you will needto temporarily up the console loglevel usingalt-sysrq-8 or:

echo 8 > /proc/sysrq-trigger

Remember to return the loglevel to normal after triggering the sysrqcommand you are interested in.

I have more questions, who can I ask?

Just ask them on the linux-kernel mailing list:
linux-kernel@vger.kernel.org

Credits