a bit closer

This commit is contained in:
Ciro Santilli
2018-02-13 16:09:16 +00:00
parent d97d461605
commit 64130ecfb9
22 changed files with 316 additions and 569 deletions

View File

@@ -1,5 +1,4 @@
[[contributing]] === CONTRIBUTING
= CONTRIBUTING
Testing you should do before pushing: new modules: Testing you should do before pushing: new modules:

View File

@@ -1,68 +1,17 @@
[[linux-kernel-module-cheat]]
= Linux Kernel Module Cheat = Linux Kernel Module Cheat
Run one command, get a QEMU Buildroot BusyBox virtual machine built from Run one command, get a QEMU Buildroot BusyBox virtual machine built from source with several minimal Linux kernel 4.15 module development example tutorials with GDB and KGDB step debugging and minimal educational hardware models. Limited GEM5 full system support. "Tested" in x86, ARM and MIPS guests, Ubuntu 17.10 host.
source with several minimal Linux kernel 4.15 module development example
tutorials with GDB and KGDB step debugging and minimal educational
hardware models. Limited GEM5 full system support. "Tested" in x86, ARM
and MIPS guests, Ubuntu 17.10 host.
image:screenshot.png[image]
Reserve 12Gb of disk and run:
....
git clone https://github.com/cirosantilli/linux-kernel-module-cheat
cd linux-kernel-module-cheat
./configure && ./build && ./run
....
The first build will take a while
(https://stackoverflow.com/questions/10833672/buildroot-environment-with-host-toolchain[GCC],
Linux kernel), e.g.:
* 2 hours on a mid end 2012 laptop
* 30 minutes on a high end 2017 desktop
If you don't want to wait, you could also try to compile the examples
and run them on your host computer as explained on the
link:run-on-host.md["Run on host" section], but as explained on that
section, that is dangerous, limited, and will likely not work.
After QEMU opens up, you can start playing with the kernel modules:
....
root
insmod /hello.ko
insmod /hello2.ko
rmmod hello
rmmod hello2
....
This should print to the screen:
....
hello init
hello2 init
hello cleanup
hello2 cleanup
....
which are `printk` messages from `init` and `cleanup` methods of those
modules.
All available modules can be found in the
link:kernel_module/[`kernel_module` directory].
See the link:getting-started.md[getting started section] for further
details.
1. link:getting-started.md[*Getting started*] 1. link:getting-started.md[*Getting started*]
2. Action
1. Step debugging == Action
1. link:gdb-step-debugging.md[GDB step debugging]
=== Step debugging
1. link:gdb.md[GDB step debugging]
2. link:kgdb.md[KGDB] 2. link:kgdb.md[KGDB]
3. link:gdbserver.md[gdbserver] 3. link:gdbserver.md[gdbserver]
2. link:other-architectures.md[Other architectures] 2. link:other-architectures.md[Other architectures]
3. link:init.md[init] 3. link:init.md[init]
4. link:modprobe.md[modprobe] 4. link:modprobe.md[modprobe]
@@ -71,13 +20,22 @@ details.
7. link:gem5.md[GEM5] 7. link:gem5.md[GEM5]
8. link:ftrace.md[ftrace] 8. link:ftrace.md[ftrace]
9. link:qemu-user-mode.md[QEMU user mode] 9. link:qemu-user-mode.md[QEMU user mode]
3. Failed action 10. link:snapshot.md[Snapshot]
== Failed action
1. link:record-and-replay.md[Record and replay] 1. link:record-and-replay.md[Record and replay]
4. Insane action
== Insane action
1. link:run-on-host.md[Run on host] 1. link:run-on-host.md[Run on host]
2. link:hello_host/[Hello host] 2. link:hello_host/[Hello host]
5. Conversation
== Conversation
1. link:kmod.md[kmod] 1. link:kmod.md[kmod]
2. link:device-tree.md[Device tree] 2. link:device-tree.md[Device tree]
3. link:maintainers.md[Maintainers] 3. link:maintainers.md[Maintainers]
4. link:bibliography.md[Bibliography] 4. link:bibliography.md[Bibliography]
image:screenshot.png[image]

View File

@@ -1,29 +1,16 @@
[[bibliography]] === Bibliography
= Bibliography
Runnable stuff: Runnable stuff:
* https://lwn.net/Kernel/LDD3/ the best book, but outdated. Updated * https://lwn.net/Kernel/LDD3/ the best book, but outdated. Updated source: https://github.com/martinezjavier/ldd3 But examples non-minimal and take too much brain power to understand.
source: https://github.com/martinezjavier/ldd3 But examples non-minimal * https://github.com/satoru-takeuchi/elkdat manual build process without Buildroot, very few and simple kernel modules
and take too much brain power to understand. * https://github.com/tinyclub/linux-lab Buildroot based, no kernel modules?
* https://github.com/satoru-takeuchi/elkdat manual build process without
Buildroot, very few and simple kernel modules
* https://github.com/tinyclub/linux-lab Buildroot based, no kernel
modules?
* https://github.com/agelastic/eudyptula * https://github.com/agelastic/eudyptula
* https://github.com/linux-kernel-labs Yocto based, source inside a * https://github.com/linux-kernel-labs Yocto based, source inside a kernel fork subdir: https://github.com/linux-kernel-labs/linux/tree/f08b9e4238dfc612a9d019e3705bd906930057fc/tools/labs which the author would like to upstream https://www.reddit.com/r/programming/comments/79w2q9/linux_device_driver_labs_the_linux_kernel/dp6of43/
kernel fork subdir: * Android AOSP: https://stackoverflow.com/questions/1809774/how-to-compile-the-android-aosp-kernel-and-test-it-with-the-android-emulator/48310014#48310014 AOSP is basically a uber bloated Buildroot, Android is Linux based, and QEMU is the emulator backend.
https://github.com/linux-kernel-labs/linux/tree/f08b9e4238dfc612a9d019e3705bd906930057fc/tools/labs
which the author would like to upstream
https://www.reddit.com/r/programming/comments/79w2q9/linux_device_driver_labs_the_linux_kernel/dp6of43/
* Android AOSP:
https://stackoverflow.com/questions/1809774/how-to-compile-the-android-aosp-kernel-and-test-it-with-the-android-emulator/48310014#48310014
AOSP is basically a uber bloated Buildroot, Android is Linux based, and
QEMU is the emulator backend.
Theory: Theory:
* https://lwn.net * https://lwn.net
* http://www.makelinux.net * http://www.makelinux.net
* http://nairobi-embedded.org/ you will fall here a lot when the hard * http://nairobi-embedded.org/ you will fall here a lot when the hard Google queries start popping
Google queries start popping

View File

@@ -1,5 +1,4 @@
[[count-boot-instructions]] === Count boot instructions
= Count boot instructions
* https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take * https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take
* https://github.com/cirosantilli/chat/issues/31 * https://github.com/cirosantilli/chat/issues/31
@@ -19,21 +18,13 @@ time ./run -n -e 'init=/poweroff.out' -- -trace exec_tb,file=trace && \
Notes: Notes:
* `-n` is a good idea to reduce the chances that you send unwanted * `-n` is a good idea to reduce the chances that you send unwanted non-deterministic mouse or keyboard clicks to the VM.
non-deterministic mouse or keyboard clicks to the VM. * `-e 'init=/poweroff.out'` is crucial as it reduces the instruction count from 40 million to 20 million, so half of the instructions were due to userland programs instead of the boot sequence.
* `-e 'init=/poweroff.out'` is crucial as it reduces the instruction
count from 40 million to 20 million, so half of the instructions were
due to userland programs instead of the boot sequence.
+ +
Without it, the bulk of the time seems to be spent in setting up the Without it, the bulk of the time seems to be spent in setting up the network with `ifup` that gets called from `/etc/init.d/S40network` from the default Buildroot BusyBox setup.
network with `ifup` that gets called from `/etc/init.d/S40network` from
the default Buildroot BusyBox setup.
+ +
And it becomes even worse if you try to `-net none` as recommended in And it becomes even worse if you try to `-net none` as recommended in the 2.7 `replay.txt` docs, because then `ifup` waits for 15 seconds before giving up as per `/etc/network/interfaces` line `wait-delay 15`.
the 2.7 `replay.txt` docs, because then `ifup` waits for 15 seconds * `0x1000000` is the address where QEMU puts the Linux kernel at with `-kernel` in x86.
before giving up as per `/etc/network/interfaces` line `wait-delay 15`.
* `0x1000000` is the address where QEMU puts the Linux kernel at with
`-kernel` in x86.
+ +
It can be found from: It can be found from:
+ +
@@ -47,55 +38,37 @@ TODO confirm further. If I try to break there with:
./rungdb *0x1000000 ./rungdb *0x1000000
.... ....
+ +
but I have no corresponding source line. Also note that this line is not but I have no corresponding source line. Also note that this line is not actually the first line, since the kernel messages such as `early console in extract_kernel` have already shown on screen at that point. This does not break at all:
actually the first line, since the kernel messages such as
`early console in extract_kernel` have already shown on screen at that
point. This does not break at all:
+ +
.... ....
./rungdb extract_kernel ./rungdb extract_kernel
.... ....
+ +
It only appears once on every log I've seen so far, checked with It only appears once on every log I've seen so far, checked with `grep 0x1000000 trace.txt`
`grep 0x1000000 trace.txt`
+ +
Then when we count the instructions that run before the kernel entry Then when we count the instructions that run before the kernel entry point, there is only about 100k instructions, which is insignificant compared to the kernel boot itself.
point, there is only about 100k instructions, which is insignificant * We can also discount the instructions after `init` runs by using `readelf` to get the initial address of `init`. One easy way to do that now is to just run:
compared to the kernel boot itself.
* We can also discount the instructions after `init` runs by using
`readelf` to get the initial address of `init`. One easy way to do that
now is to just run:
+ +
.... ....
./rungdb-user kernel_module-1.0/user/poweroff.out main ./rungdb-user kernel_module-1.0/user/poweroff.out main
.... ....
+ +
And get that from the traces, e.g. if the address is `4003a0`, then we And get that from the traces, e.g. if the address is `4003a0`, then we search:
search:
+ +
.... ....
grep -n 4003a0 trace.txt grep -n 4003a0 trace.txt
.... ....
+ +
I have observed a single match for that instruction, so it must be the I have observed a single match for that instruction, so it must be the init, and there were only 20k instructions after it, so the impact is negligible.
init, and there were only 20k instructions after it, so the impact is
negligible.
This works because we have already done the following with QEMU: This works because we have already done the following with QEMU:
* `./configure --enable-trace-backends=simple`. This logs in a binary * `./configure --enable-trace-backends=simple`. This logs in a binary format to the trace file.
format to the trace file.
+ +
It makes 3x execution faster than the default trace backend which logs It makes 3x execution faster than the default trace backend which logs human readable data to stdout.
human readable data to stdout.
+ +
This also alters the actual execution, and reduces the instruction count This also alters the actual execution, and reduces the instruction count by 10M TODO understand exactly why, possibly due to the `All QSes seen` thing.
by 10M TODO understand exactly why, possibly due to the `All QSes seen` * the simple QEMU patch mentioned at: https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/ of removing the `disable` from `exec_tb` in the `trace-events` template file in the QEMU source
thing.
* the simple QEMU patch mentioned at:
https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/ of
removing the `disable` from `exec_tb` in the `trace-events` template
file in the QEMU source
Possible improvements: Possible improvements:
@@ -103,10 +76,8 @@ Possible improvements:
** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled ** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled
** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015 ** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015
+ +
`CONFIG_NET=n` did not significantly reduce instruction, so maybe `CONFIG_NET=n` did not significantly reduce instruction, so maybe replacing `init` is enough.
replacing `init` is enough. * logging with the default backend `log` greatly slows down the CPU, and in particular leads to this during kernel boot:
* logging with the default backend `log` greatly slows down the CPU, and
in particular leads to this during kernel boot:
+ +
.... ....
All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0 All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
@@ -121,5 +92,4 @@ Call Trace:
.... ....
+ +
in which the boot appears to hang for a considerable time. in which the boot appears to hang for a considerable time.
* Confirm that the kernel enters at `0x1000000`, or where it enters. * Confirm that the kernel enters at `0x1000000`, or where it enters. Once we have this, we can exclude what comes before in the BIOS.
Once we have this, we can exclude what comes before in the BIOS.

View File

@@ -1,8 +1,6 @@
[[device-tree]] === Device tree
= Device tree
`platform_device.c` together with its kernel and QEMU forks contains a `platform_device.c` together with its kernel and QEMU forks contains a minimal runnable example.
minimal runnable example.
Good format descriptions: Good format descriptions:

View File

@@ -1,5 +1,4 @@
[[ftrace]] === ftrace
= ftrace
Trace a single function: Trace a single function:
@@ -92,5 +91,4 @@ Sample output:
TODO: what do `+` and `!` mean? TODO: what do `+` and `!` mean?
Each `enable` under the `events/` tree enables a certain set of Each `enable` under the `events/` tree enables a certain set of functions, the higher the `enable` more functions are enabled.
functions, the higher the `enable` more functions are enabled.

View File

@@ -1,5 +1,4 @@
[[gdb-step-debugging]] === GDB step debugging
= GDB step debugging
To GDB step debug the Linux kernel, first run: To GDB step debug the Linux kernel, first run:
@@ -7,8 +6,7 @@ To GDB step debug the Linux kernel, first run:
./run -d ./run -d
.... ....
If you want to break immediately at a symbol, e.g. `start_kernel` of the If you want to break immediately at a symbol, e.g. `start_kernel` of the boot sequence, run on another shell:
boot sequence, run on another shell:
.... ....
./rungdb start_kernel ./rungdb start_kernel
@@ -53,21 +51,15 @@ See also:
* http://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642 * http://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642
* http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607 * http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607
`O=0` is an impossible dream, `O=2` being the default: `O=0` is an impossible dream, `O=2` being the default: https://stackoverflow.com/questions/29151235/how-to-de-optimize-the-linux-kernel-to-and-compile-it-with-o0 So get ready for some weird jumps, and `<value optimized out>` fun. Why, Linux, why.
https://stackoverflow.com/questions/29151235/how-to-de-optimize-the-linux-kernel-to-and-compile-it-with-o0
So get ready for some weird jumps, and `<value optimized out>` fun. Why,
Linux, why.
[[kernel-module-debugging]] ==== Kernel module debugging
== Kernel module debugging
Loadable kernel modules are a bit trickier since the kernel can place Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.
them at different memory locations depending on load order.
So we cannot set the breakpoints before `insmod`. So we cannot set the breakpoints before `insmod`.
However, the Linux kernel GDB scripts offer the `lx-symbols` command, However, the Linux kernel GDB scripts offer the `lx-symbols` command, which takes care of that beautifully for us:
which takes care of that beautifully for us:
.... ....
./run -d ./run -d
@@ -102,17 +94,13 @@ printf a >/sys/kernel/debug/lkmc_fops/f
and GDB now breaks at our `fop_write` function! and GDB now breaks at our `fop_write` function!
Just don't forget to remove your breakpoints after `rmmod`, or they will Just don't forget to remove your breakpoints after `rmmod`, or they will point to stale memory locations.
point to stale memory locations.
TODO: why does `break work_func` for `insmod kthread.ko` not break the TODO: why does `break work_func` for `insmod kthread.ko` not break the first time I `insmod`, but breaks the second time?
first time I `insmod`, but breaks the second time?
See also: See also: http://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
http://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
[[bypassing-lx-symbols]] ===== Bypassing lx-symbols
=== Bypassing lx-symbols
Useless, but a good way to show how hardcore you are. From inside QEMU: Useless, but a good way to show how hardcore you are. From inside QEMU:
@@ -134,8 +122,7 @@ Ctrl + C
add-symbol-file ../kernel_module-1.0/fops.ko 0xfffffffa00000000 add-symbol-file ../kernel_module-1.0/fops.ko 0xfffffffa00000000
.... ....
[[debug-kernel-early-boot]] ==== Debug kernel early boot
== Debug kernel early boot
TODO: why can't we break at early startup stuff such as: TODO: why can't we break at early startup stuff such as:
@@ -144,5 +131,38 @@ TODO: why can't we break at early startup stuff such as:
./rungdb main ./rungdb main
.... ....
See also: See also: https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
==== call
GDB can call functions as explained at: https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb
However this is failing for us:
* some symbols are not visible to `call` even though `b` sees them
* for those that are, `call` fails with an E14 error
E.g.: if we break on `sys_write` on `/count.sh`:
....
>>> call printk(0, "asdf")
Could not fetch register "orig_rax"; remote failure reply 'E14'
>>> b printk
Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
>>> call fdget_pos(fd)
No symbol "fdget_pos" in current context.
>>> b fdget_pos
Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
>>>
....
even though `fdget_pos` is the first thing `sys_write` does:
....
581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
582 size_t, count)
583 {
584 struct fd f = fdget_pos(fd);
....
See also: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/19

View File

@@ -1,8 +1,6 @@
[[gdbserver]] === gdbserver
= gdbserver
Step debug userland processes to understand how they are talking to the Step debug userland processes to understand how they are talking to the kernel.
kernel.
In guest: In guest:
@@ -24,15 +22,8 @@ find buildroot/output.x86_64~/build -name myinsmod.out
TODO: automate the path finding: TODO: automate the path finding:
* using the executable from under `buildroot/output.x86_64~/target` * using the executable from under `buildroot/output.x86_64~/target` would be easier as the path is the same as in guest, but unfortunately those executables are stripped to make the guest smaller. `BR2_STRIP_none=y` should disable stripping, but make the image way larger.
would be easier as the path is the same as in guest, but unfortunately * `outputx86_64~/staging/` would be even better than `target/` as the docs say that this directory contains binaries before they were stripped. However, only a few binaries are pre-installed there by default, and it seems to be a manual per package thing.
those executables are stripped to make the guest smaller.
`BR2_STRIP_none=y` should disable stripping, but make the image way
larger.
* `outputx86_64~/staging/` would be even better than `target/` as the
docs say that this directory contains binaries before they were
stripped. However, only a few binaries are pre-installed there by
default, and it seems to be a manual per package thing.
+ +
E.g. `pciutils` has for `lspci`: E.g. `pciutils` has for `lspci`:
+ +
@@ -44,16 +35,13 @@ define PCIUTILS_INSTALL_STAGING_CMDS
endef endef
.... ....
+ +
and the docs describe the `*_INSTALL_STAGING` per package config, which and the docs describe the `*_INSTALL_STAGING` per package config, which is normally set for shared library packages.
is normally set for shared library packages.
+ +
Feature request: https://bugs.busybox.net/show_bug.cgi?id=10386 Feature request: https://bugs.busybox.net/show_bug.cgi?id=10386
An implementation overview can be found at: An implementation overview can be found at: https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-mips-elf-with-qemu-toolchain/16214#16214
https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-mips-elf-with-qemu-toolchain/16214#16214
[[gdbserver-different-archs]] ==== gdbserver different archs
== gdbserver different archs
As usual, different archs work with: As usual, different archs work with:
@@ -61,8 +49,7 @@ As usual, different archs work with:
./rungdbserver -a arm kernel_module-1.0/user/myinsmod.out ./rungdbserver -a arm kernel_module-1.0/user/myinsmod.out
.... ....
[[gdbserver-busybox]] ==== gdbserver BusyBox
== gdbserver BusyBox
BusyBox executables are all symlinks, so if you do on guest: BusyBox executables are all symlinks, so if you do on guest:
@@ -76,11 +63,9 @@ on host you need:
./rungdbserver busybox-1.26.2/busybox ./rungdbserver busybox-1.26.2/busybox
.... ....
[[gdbserver-shared-libraries]] ==== gdbserver shared libraries
== gdbserver shared libraries
Our setup gives you the rare opportunity to step debug libc and other Our setup gives you the rare opportunity to step debug libc and other system libraries e.g. with:
system libraries e.g. with:
.... ....
b open b open
@@ -99,27 +84,20 @@ This is made possible by the GDB command:
set sysroot ${buildroot_out_dir}/staging set sysroot ${buildroot_out_dir}/staging
.... ....
which automatically finds unstripped shared libraries on the host for which automatically finds unstripped shared libraries on the host for us.
us.
See also: See also: https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
[[debug-userland-process-without-gdbserver]] ==== Debug userland process without gdbserver
== Debug userland process without gdbserver
QEMU `-gdb` GDB breakpoints are set on virtual addresses, so you can in QEMU `-gdb` GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.
theory debug userland processes as well.
* https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel * https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel
* https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb * https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb
The only use case I can see for this is to debug the init process (and The only use case I can see for this is to debug the init process (and have fun), otherwise, why wouldn't you just use `gdbserver`? Known limitations of direct userland debugging:
have fun), otherwise, why wouldn't you just use `gdbserver`? Known
limitations of direct userland debugging:
* the kernel might switch context to another process, and you would * the kernel might switch context to another process, and you would enter "garbage"
enter "garbage"
* TODO step into shared libraries. If I attempt to load them explicitly: * TODO step into shared libraries. If I attempt to load them explicitly:
+ +
.... ....
@@ -155,8 +133,7 @@ BusyBox custom init process:
./rungdb-user -h busybox-1.26.2/busybox ls_main ./rungdb-user -h busybox-1.26.2/busybox ls_main
.... ....
This follows BusyBox' convention of calling the main for each executable This follows BusyBox' convention of calling the main for each executable as `<exec>_main` since the `busybox` executable has many "mains".
as `<exec>_main` since the `busybox` executable has many "mains".
BusyBox default init process: BusyBox default init process:
@@ -171,8 +148,7 @@ BusyBox default init process:
./rungdb-user -h busybox-1.26.2/busybox init_main ./rungdb-user -h busybox-1.26.2/busybox init_main
.... ....
This cannot be debugged in another way without modifying the source, or This cannot be debugged in another way without modifying the source, or `/sbin/init` exits early with:
`/sbin/init` exits early with:
.... ....
"must be run as PID 1" "must be run as PID 1"
@@ -199,5 +175,4 @@ continue
/sleep_forever.out /sleep_forever.out
.... ....
This is of least reliable setup as there might be other processes that This is of least reliable setup as there might be other processes that use the given virtual address.
use the given virtual address.

122
gem5.adoc
View File

@@ -1,45 +1,27 @@
[[gem5]] === GEM5
= GEM5
[[introduction]] ==== Introduction
== Introduction
GEM5 is a system simulator, much like QEMU: http://gem5.org/ GEM5 is a system simulator, much like QEMU: http://gem5.org/
Vs QEMU: Vs QEMU:
* advantage: simulates a generic more realistic pipelined and optionally * advantage: simulates a generic more realistic pipelined and optionally out of order CPU cycle by cycle, including a realistic DRAM memory access model with latencies, caches and page table manipulations. This allows us to:
out of order CPU cycle by cycle, including a realistic DRAM memory ** do much more realistic performance benchmarking with it, which makes absolutely no sense in QEMU, which is purely functional
access model with latencies, caches and page table manipulations. This ** make functional cache observations, e.g. to use Linux kernel APIs that flush memory like DMA, which are crucial for driver development. In QEMU, the driver would still work even if we forget to flush caches.
allows us to:
** do much more realistic performance benchmarking with it, which makes
absolutely no sense in QEMU, which is purely functional
** make functional cache observations, e.g. to use Linux kernel APIs
that flush memory like DMA, which are crucial for driver development. In
QEMU, the driver would still work even if we forget to flush caches.
+ +
It is not of course truly cycle accurate, as that would require exposing It is not of course truly cycle accurate, as that would require exposing proprietary information of the CPU designs: https://stackoverflow.com/questions/17454955/can-you-check-performance-of-a-program-running-with-qemu-simulator/33580850#33580850, but the approximation is reasonable.
proprietary information of the CPU designs:
https://stackoverflow.com/questions/17454955/can-you-check-performance-of-a-program-running-with-qemu-simulator/33580850#33580850,
but the approximation is reasonable.
+ +
It is used mostly for research purposes: when you are making a new chip It is used mostly for research purposes: when you are making a new chip technology, you don't really need to specialize enormously to an existing microarchitecture, but rather develop something that will work with a wide range of future architectures.
technology, you don't really need to specialize enormously to an
existing microarchitecture, but rather develop something that will work
with a wide range of future architectures.
* disadvantage: slower than QEMU by TODO 10x? * disadvantage: slower than QEMU by TODO 10x?
+ +
This also implies that the user base is much smaller, since no Android This also implies that the user base is much smaller, since no Android devs.
devs.
+ +
Instead, we have only chip makers, who keep everything that really works Instead, we have only chip makers, who keep everything that really works closed, and researchers, who can't version track or document code properly >:-) And this implies that:
closed, and researchers, who can't version track or document code
properly >:-) And this implies that:
** the documentation is more scarce ** the documentation is more scarce
** it takes longer to support new hardware features ** it takes longer to support new hardware features
[[arm]] ==== ARM
== ARM
.... ....
./configure && ./build -a arm-gem5 ./configure && ./build -a arm-gem5
@@ -52,8 +34,7 @@ On another shell:
./rungem5-shell ./rungem5-shell
.... ....
[[kernel-command-line-arguments]] ===== Kernel command line arguments
=== Kernel command line arguments
E.g., to add `printk.time=y`, run: E.g., to add `printk.time=y`, run:
@@ -61,11 +42,9 @@ E.g., to add `printk.time=y`, run:
./rungem5 -a arm-gem5 -- --command-line='earlyprintk=pl011,0x1c090000 console=ttyAMA0 lpj=19988480 norandmaps rw loglevel=8 mem=512MB root=/dev/sda printk.time=y' ./rungem5 -a arm-gem5 -- --command-line='earlyprintk=pl011,0x1c090000 console=ttyAMA0 lpj=19988480 norandmaps rw loglevel=8 mem=512MB root=/dev/sda printk.time=y'
.... ....
When you use `--command-line=`, it overrides default command lines, When you use `--command-line=`, it overrides default command lines, which are required to boot properly.
which are required to boot properly.
So if you pass just `--command-line='printk.time=y'`, it removes the So if you pass just `--command-line='printk.time=y'`, it removes the required options, and boot fails.
required options, and boot fails.
An easy way to find the other options is to to an initial boot: An easy way to find the other options is to to an initial boot:
@@ -79,17 +58,13 @@ and then look at the line of the linux kernel that starts with
Kernel command line: Kernel command line:
.... ....
We might copy the default `--command-line` into our startup scripts to We might copy the default `--command-line` into our startup scripts to make things easier at some point, but it would be fun to debug when the defaults change upstream and we don't notice :-(
make things easier at some point, but it would be fun to debug when the
defaults change upstream and we don't notice :-(
[[qemu-with-gem5-kernel-configuration]] ===== QEMU with GEM5 kernel configuration
=== QEMU with GEM5 kernel configuration
TODO: QEMU did not work with the GEM5 kernel configurations. TODO: QEMU did not work with the GEM5 kernel configurations.
To test this, hack up `run` to use the `buildroot/output.arm-gem5~` To test this, hack up `run` to use the `buildroot/output.arm-gem5~` directory, and then run:
directory, and then run:
.... ....
./run -a arm ./run -a arm
@@ -107,8 +82,7 @@ and the display shows:
Guest has not initialized the display (yet). Guest has not initialized the display (yet).
.... ....
[[gem5-with-qemu-kernel-configuration]] ===== GEM5 with QEMU kernel configuration
=== GEM5 with QEMU kernel configuration
Test it out with: Test it out with:
@@ -135,11 +109,9 @@ Escape character is '^]'.
==== m5 slave terminal: Terminal 0 ==== ==== m5 slave terminal: Terminal 0 ====
.... ....
I have also tried to copy the exact same kernel command line options I have also tried to copy the exact same kernel command line options used by QEMU, but nothing changed.
used by QEMU, but nothing changed.
[[x86]] ==== x86
== x86
TODO didn't get it working yet. TODO didn't get it working yet.
@@ -147,11 +119,9 @@ Related threads:
* https://www.mail-archive.com/gem5-users@gem5.org/msg11384.html * https://www.mail-archive.com/gem5-users@gem5.org/msg11384.html
* https://stackoverflow.com/questions/37906425/booting-gem5-x86-ubuntu-full-system-simulation * https://stackoverflow.com/questions/37906425/booting-gem5-x86-ubuntu-full-system-simulation
* http://www.lowepower.com/jason/creating-disk-images-for-gem5.html * http://www.lowepower.com/jason/creating-disk-images-for-gem5.html claims to have a working config for x86_64 kernel 4.8.13
claims to have a working config for x86_64 kernel 4.8.13
[[our-best-attempt]] ===== Our best attempt
=== Our best attempt
.... ....
./configure && ./build -a x86_64-gem5 ./configure && ./build -a x86_64-gem5
@@ -174,32 +144,23 @@ Memory Usage: 1235908 KBytes
Program aborted at tick 427627410500 Program aborted at tick 427627410500
.... ....
The same failure happens if we use the working QEMU Linux kernel, and / The same failure happens if we use the working QEMU Linux kernel, and / or if we use the kernel 4.8.13 as proposed in lowepower's post..
or if we use the kernel 4.8.13 as proposed in lowepower's post..
If we look a bit into the source, the panic message comes from If we look a bit into the source, the panic message comes from `i8042.cc`, and on the header we see that the missing command is:
`i8042.cc`, and on the header we see that the missing command is:
.... ....
WriteOutputPort = 0xD1, WriteOutputPort = 0xD1,
.... ....
The kernel was compiled with `CONFIG_SERIO_I8042=y`, I didn't dare The kernel was compiled with `CONFIG_SERIO_I8042=y`, I didn't dare disable it yet. The Linux kernel driver has no `grep` hits for either of `0xd1` nor `output.?port`, it must be using some random bitmask to build it then.
disable it yet. The Linux kernel driver has no `grep` hits for either of
`0xd1` nor `output.?port`, it must be using some random bitmask to build
it then.
This byte is documented at This byte is documented at http://wiki.osdev.org/%228042%22_PS/2_Controller, as usual :-)
http://wiki.osdev.org/%228042%22_PS/2_Controller, as usual :-)
There are also a bunch of `i8042` kernel CLI options, I tweaked all of There are also a bunch of `i8042` kernel CLI options, I tweaked all of them but nothing.
them but nothing.
[[working-baseline-with-magic-image]] ===== Working baseline with magic image
=== Working baseline with magic image
Working x86 with the pre-built magic image with an ancient 2.6.22.9 Working x86 with the pre-built magic image with an ancient 2.6.22.9 kernel starting point:
kernel starting point:
.... ....
sudo mkdir -p /dist/m5/system sudo mkdir -p /dist/m5/system
@@ -232,14 +193,11 @@ On another shell:
telnet localhost 3456 telnet localhost 3456
.... ....
[[unmodified-buildroot-images-2]] ===== Unmodified Buildroot images 2
=== Unmodified Buildroot images 2
bzImage fails, so we always try with vmlinux obtained from inside bzImage fails, so we always try with vmlinux obtained from inside build/.
build/.
rootfs.ext2 and vmlinux from rootfs.ext2 and vmlinux from 670366caaded57d318b6dbef34e863e3b30f7f29ails as:
670366caaded57d318b6dbef34e863e3b30f7f29ails as:
Fails as: Fails as:
@@ -307,11 +265,9 @@ ALSA device list:
No soundcards found. No soundcards found.
.... ....
So just looks like we have to disable some Linux configs which GEM5 does So just looks like we have to disable some Linux configs which GEM5 does not support... so fragile.
not support... so fragile.
[[copy-upstream-2.6-configs-on-4.9-kernel]] ===== Copy upstream 2.6 configs on 4.9 kernel
=== Copy upstream 2.6 configs on 4.9 kernel
The magic image provides its kernel configurations, so let's try that. The magic image provides its kernel configurations, so let's try that.
@@ -323,9 +279,7 @@ wget http://www.gem5.org/dist/current/x86/config-x86.tar.bz2
backed up at: https://github.com/cirosantilli/media/releases/tag/gem5 backed up at: https://github.com/cirosantilli/media/releases/tag/gem5
Copy `linux-2.6.22.9` into the kernel tree as `.config`, Copy `linux-2.6.22.9` into the kernel tree as `.config`, `git checkout v4.9.6`, `make olddefconfig`, `make`, then use the Buildroot filesystem as above, failure:
`git checkout v4.9.6`, `make olddefconfig`, `make`, then use the
Buildroot filesystem as above, failure:
.... ....
panic: Invalid IDE control register offset: 0 panic: Invalid IDE control register offset: 0
@@ -368,10 +322,6 @@ Program aborted at tick 382834812000
Aborted (core dumped) Aborted (core dumped)
.... ....
[[use-upstream-2.6-configs-and-2.6-kernel]] ===== Use upstream 2.6 configs and 2.6 kernel
=== Use upstream 2.6 configs and 2.6 kernel
If we checkout to the ancient kernel `v2.6.22.9`, it fails to compile If we checkout to the ancient kernel `v2.6.22.9`, it fails to compile with modern GNU make 4.1: https://stackoverflow.com/questions/35002691/makefile-make-clean-why-getting-mixed-implicit-and-normal-rules-deprecated-s lol
with modern GNU make 4.1:
https://stackoverflow.com/questions/35002691/makefile-make-clean-why-getting-mixed-implicit-and-normal-rules-deprecated-s
lol

View File

@@ -1,35 +1,65 @@
= Getting started === Getting started
:toc: macro
toc::[] Reserve 12Gb of disk and run:
[[module-documentation]] ....
== Module documentation git clone https://github.com/cirosantilli/linux-kernel-module-cheat
cd linux-kernel-module-cheat
./configure && ./build && ./run
....
The first build will take a while (https://stackoverflow.com/questions/10833672/buildroot-environment-with-host-toolchain[GCC], Linux kernel), e.g.:
* 2 hours on a mid end 2012 laptop
* 30 minutes on a high end 2017 desktop
If you don't want to wait, you could also try to compile the examples and run them on your host computer as explained on the link:run-on-host.md["Run on host" section], but as explained on that section, that is dangerous, limited, and will likely not work.
After QEMU opens up, you can start playing with the kernel modules:
....
root
insmod /hello.ko
insmod /hello2.ko
rmmod hello
rmmod hello2
....
This should print to the screen:
....
hello init
hello2 init
hello cleanup
hello2 cleanup
....
which are `printk` messages from `init` and `cleanup` methods of those modules.
All available modules can be found in the link:kernel_module/[`kernel_module` directory].
==== Module documentation
.... ....
head kernel_module/modulename.c head kernel_module/modulename.c
.... ....
Many of the modules have userland test scripts / executables with the Many of the modules have userland test scripts / executables with the same name as the module, e.g. form inside the guest:
same name as the module, e.g. form inside the guest:
.... ....
/modulename.sh /modulename.sh
/modulename.out /modulename.out
.... ....
The sources of those tests will further clarify what the corresponding The sources of those tests will further clarify what the corresponding kernel modules does. To find them on the host, do a quick:
kernel modules does. To find them on the host, do a quick:
.... ....
git ls-files | grep modulename git ls-files | grep modulename
.... ....
[[rebuild]] ==== Rebuild
== Rebuild
If you make changes to the kernel modules or most configurations tracked If you make changes to the kernel modules or most configurations tracked on this repository, you can just use again:
on this repository, you can just use again:
.... ....
./build ./build
@@ -38,8 +68,7 @@ on this repository, you can just use again:
and the modified files will be rebuilt. and the modified files will be rebuilt.
If you change any package besides `kernel_module`, you must also request If you change any package besides `kernel_module`, you must also request those packages to be reconfigured or rebuilt with extra targets, e.g.:
those packages to be reconfigured or rebuilt with extra targets, e.g.:
.... ....
./build -t linux-reconfigure -t host-qemu-reconfigure ./build -t linux-reconfigure -t host-qemu-reconfigure
@@ -47,8 +76,7 @@ those packages to be reconfigured or rebuilt with extra targets, e.g.:
Those aren't turned on by default because they take quite a few seconds. Those aren't turned on by default because they take quite a few seconds.
[[filesystem-persistency]] ==== Filesystem persistency
== Filesystem persistency
The root filesystem is persistent across: The root filesystem is persistent across:
@@ -66,8 +94,7 @@ then:
cat f cat f
.... ....
This is particularly useful to re-run shell commands from the history of This is particularly useful to re-run shell commands from the history of a previous session with `Ctrl + R`.
a previous session with `Ctrl + R`.
However, when you do: However, when you do:
@@ -75,25 +102,19 @@ However, when you do:
./build ./build
.... ....
the disk image gets overwritten by a fresh filesystem and you lose all the disk image gets overwritten by a fresh filesystem and you lose all changes.
changes.
Remember that if you forcibly turn QEMU off without `sync` or `poweroff` Remember that if you forcibly turn QEMU off without `sync` or `poweroff` from inside the VM, e.g. by closing the QEMU window, disk changes may not be saved.
from inside the VM, e.g. by closing the QEMU window, disk changes may
not be saved.
[[message-control]] ==== Message control
== Message control
We use `printk` a lot, and it shows on the QEMU terminal by default. If We use `printk` a lot, and it shows on the QEMU terminal by default. If that annoys you (e.g. you want to see stdout separately), do:
that annoys you (e.g. you want to see stdout separately), do:
.... ....
dmesg -n 1 dmesg -n 1
.... ....
See also: See also: https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
You can scroll up a bit on the default TTY with: You can scroll up a bit on the default TTY with:
@@ -108,11 +129,9 @@ but I never managed to increase that buffer:
The superior alternative is to use text mode or a telnet connection. The superior alternative is to use text mode or a telnet connection.
[[text-mode]] ==== Text mode
== Text mode
Show serial console directly on the current terminal, without opening a Show serial console directly on the current terminal, without opening a QEMU window:
QEMU window:
.... ....
./run -n ./run -n
@@ -126,16 +145,11 @@ poweroff
This mode is very useful to: This mode is very useful to:
* get full panic traces when you start making the kernel crash :-) See * get full panic traces when you start making the kernel crash :-) See also: https://unix.stackexchange.com/questions/208260/how-to-scroll-up-after-a-kernel-panic
also:
https://unix.stackexchange.com/questions/208260/how-to-scroll-up-after-a-kernel-panic
* copy and paste commands and stdout output to / from host * copy and paste commands and stdout output to / from host
* have a large scroll buffer, and be able to search it, e.g. by using * have a large scroll buffer, and be able to search it, e.g. by using GNU `screen` on host
GNU `screen` on host
If the system crashes and you can't can quit QEMU with `poweroff`, or if If the system crashes and you can't can quit QEMU with `poweroff`, or if `poweroff` is just too slow for your patience, you can hard kill the VM with
`poweroff` is just too slow for your patience, you can hard kill the VM
with
.... ....
Ctrl-C X Ctrl-C X
@@ -170,22 +184,16 @@ See also:
Limitations: Limitations:
* TODO: Ctrl + C kills the emulator for some setups (TODO which what * TODO: Ctrl + C kills the emulator for some setups (TODO which what exactly?), and not sent to guest processes. See:
exactly?), and not sent to guest processes. See:
** https://github.com/cloudius-systems/osv/issues/49 ** https://github.com/cloudius-systems/osv/issues/49
** https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-in-qemu ** https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-in-qemu
+ +
This is however fortunate when running QEMU with GDB, as the Ctrl + C This is however fortunate when running QEMU with GDB, as the Ctrl + C reaches GDB and breaks.
reaches GDB and breaks. * Very early kernel messages such as `early console in extract_kernel` only show on the GUI, since at such early stages, not even the serial has been setup.
* Very early kernel messages such as `early console in extract_kernel`
only show on the GUI, since at such early stages, not even the serial
has been setup.
[[automatic-startup-commands]] ==== Automatic startup commands
== Automatic startup commands
When debugging a module, it becomes tedious to wait for build and When debugging a module, it becomes tedious to wait for build and re-type:
re-type:
.... ....
root root
@@ -200,8 +208,7 @@ Instead, you can either run them from a minimal init:
./run -e 'init=/eval.sh - lkmc_eval="insmod /hello.ko;/poweroff.out"' -n ./run -e 'init=/eval.sh - lkmc_eval="insmod /hello.ko;/poweroff.out"' -n
.... ....
or run them at the end of the BusyBox init, which does things like or run them at the end of the BusyBox init, which does things like setting up networking:
setting up networking:
.... ....
./run -e '- lkmc_eval="insmod /hello.ko;wget -S google.com;poweroff.out;"' ./run -e '- lkmc_eval="insmod /hello.ko;wget -S google.com;poweroff.out;"'
@@ -218,14 +225,11 @@ vim S99
and they will be run automatically before the login prompt. and they will be run automatically before the login prompt.
`S99` is a git tracked convenience symlink to the gitignored `S99` is a git tracked convenience symlink to the gitignored `rootfs_overlay/etc/init.d/S99`
`rootfs_overlay/etc/init.d/S99`
Scripts under `/etc/init.d` are run by `/etc/init.d/rcS`, which gets Scripts under `/etc/init.d` are run by `/etc/init.d/rcS`, which gets called by the line `::sysinit:/etc/init.d/rcS` in `/etc/inittab`.
called by the line `::sysinit:/etc/init.d/rcS` in `/etc/inittab`.
[[kernel-version]] ==== Kernel version
== Kernel version
We try to use the latest possible kernel major release version. We try to use the latest possible kernel major release version.
@@ -254,15 +258,11 @@ or on host:
cat buildroot/output.*~/build/linux-custom/.config cat buildroot/output.*~/build/linux-custom/.config
.... ....
[[qemu-gui-is-unresponsive]] ==== QEMU GUI is unresponsive
== QEMU GUI is unresponsive
Sometimes in Ubuntu 14.04, after the QEMU SDL GUI starts, it does not Sometimes in Ubuntu 14.04, after the QEMU SDL GUI starts, it does not get updated after keyboard strokes, and there are artifacts like disappearing text.
get updated after keyboard strokes, and there are artifacts like
disappearing text.
We have not managed to track this problem down yet, but the following We have not managed to track this problem down yet, but the following workaround always works:
workaround always works:
.... ....
Ctrl + Shift + U Ctrl + Shift + U
@@ -270,19 +270,15 @@ Ctrl + C
root root
.... ....
This started happening when we switched to building QEMU through This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.
Buildroot, and has not been observed on later Ubuntu.
Using text mode is another workaround if you don't need GUI features. Using text mode is another workaround if you don't need GUI features.
[[debug-qemu]] ==== Debug QEMU
== Debug QEMU
When you start interacting with QEMU hardware, it is useful to see what When you start interacting with QEMU hardware, it is useful to see what is going on inside of QEMU itself.
is going on inside of QEMU itself.
This is of course trivial since QEMU is just an userland program on the This is of course trivial since QEMU is just an userland program on the host, but we make it a bit easier with:
host, but we make it a bit easier with:
.... ....
./run -q ./run -q
@@ -301,16 +297,11 @@ And in QEMU:
/pci.sh /pci.sh
.... ....
Just make sure that you never click inside the QEMU window when doing Just make sure that you never click inside the QEMU window when doing that, otherwise you mouse gets captured forever, and the only solution I can find is to go to a TTY with Ctrl + Alt + F1 and `kill` QEMU.
that, otherwise you mouse gets captured forever, and the only solution I
can find is to go to a TTY with Ctrl + Alt + F1 and `kill` QEMU.
You can still send key presses to QEMU however even without the mouse You can still send key presses to QEMU however even without the mouse capture, just either click on the title bar, or alt tab to give it focus.
capture, just either click on the title bar, or alt tab to give it
focus.
[[clean-the-build]] ==== Clean the build
== Clean the build
You did something crazy, and nothing seems to work anymore? You did something crazy, and nothing seems to work anymore?

View File

@@ -1,30 +1,20 @@
[[init]] === init
= init
[[what-is-the-init-executable]] ==== What is the init executable?
== What is the init executable?
When the Linux kernel finishes booting, it runs an executable as the When the Linux kernel finishes booting, it runs an executable as the first and only userland process.
first and only userland process.
The default path is `/init`, but we an set a custom one with the `init=` The default path is `/init`, but we an set a custom one with the `init=` kernel command line argument.
kernel command line argument.
This process is then responsible for setting up the entire userland (or This process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).
destroying everything when you want to have fun).
This typically means reading some configuration files (e.g. This typically means reading some configuration files (e.g. `/etc/initrc`) and forking a bunch of userland executables based on those files.
`/etc/initrc`) and forking a bunch of userland executables based on
those files.
systemd is a "popular" `/init` implementation for desktop distros as of systemd is a "popular" `/init` implementation for desktop distros as of 2017.
2017.
BusyBox provides its own minimalistic init implementation which BusyBox provides its own minimalistic init implementation which Buildroot uses by default.
Buildroot uses by default.
[[custom-init]] ==== Custom init
== Custom init
Is the default BusyBox `/init` too bloated for you, minimalism freak? Is the default BusyBox `/init` too bloated for you, minimalism freak?
@@ -34,25 +24,20 @@ No problem, just use the `init` kernel boot parameter:
./run -e 'init=/sleep_forever.out' ./run -e 'init=/sleep_forever.out'
.... ....
Remember that shell scripts can also be used for `init` Remember that shell scripts can also be used for `init` https://unix.stackexchange.com/questions/174062/init-as-a-shell-script/395375#395375:
https://unix.stackexchange.com/questions/174062/init-as-a-shell-script/395375#395375:
.... ....
./run -e 'init=/count.sh' ./run -e 'init=/count.sh'
.... ....
Also remember that if your init returns, the kernel will panic, there Also remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:
are just two non-panic possibilities:
* run forever in a loop or long sleep * run forever in a loop or long sleep
* `poweroff` the machine * `poweroff` the machine
[[disable-networking]] ==== Disable networking
== Disable networking
The default BusyBox init scripts enable networking, and there is a 15 The default BusyBox init scripts enable networking, and there is a 15 second timeout in case your network is down or if your kernel / emulator setup does not support it.
second timeout in case your network is down or if your kernel / emulator
setup does not support it.
To disable networking, use: To disable networking, use:
@@ -66,18 +51,12 @@ To restore it, run:
./build -t initscripts-reconfigure ./build -t initscripts-reconfigure
.... ....
[[the-init-environment]] ==== The init environment
== The init environment
The docs make it clear The docs make it clear https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
_____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ _____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
The kernel parses parameters from the kernel command line up to “–”; if The kernel parses parameters from the kernel command line up to “–”; if it doesnt recognize a parameter and it doesnt contain a ., the parameter gets passed to init: parameters with = go into inits environment, others are passed as command line arguments to init. Everything after “–” is passed as an argument to init.
it doesnt recognize a parameter and it doesnt contain a ., the
parameter gets passed to init: parameters with = go into inits
environment, others are passed as command line arguments to init.
Everything after “–” is passed as an argument to init.
_____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ _____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
And you can try it out with: And you can try it out with:

View File

@@ -1,15 +1,10 @@
[[kgdb]] === KGDB
= KGDB
KGDB is kernel dark magic that allows you to GDB the kernel on real KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.
hardware without any extra hardware support.
It is useless with QEMU since we already have full system visibility It is useless with QEMU since we already have full system visibility with `-gdb`, but this is a good way to learn it.
with `-gdb`, but this is a good way to learn it.
Cheaper than JTAG (free) and easier to setup (all you need is serial), Cheaper than JTAG (free) and easier to setup (all you need is serial), but with less visibility as it depends on the kernel working, so e.g.: dies on panic, does not see boot sequence.
but with less visibility as it depends on the kernel working, so e.g.:
dies on panic, does not see boot sequence.
Usage: Usage:
@@ -43,17 +38,14 @@ c
And now you can count from GDB! And now you can count from GDB!
If you do: `b sys_write` immediately after `./rungdb -k`, it fails with If you do: `b sys_write` immediately after `./rungdb -k`, it fails with `KGDB: BP remove failed: <address>`. I think this is because it would break too early on the boot sequence, and KGDB is not yet ready.
`KGDB: BP remove failed: <address>`. I think this is because it would
break too early on the boot sequence, and KGDB is not yet ready.
See also: See also:
* https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl * https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl
* https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715 * https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715
[[kgdb-kernel-modules]] ==== KGDB kernel modules
== KGDB kernel modules
In QEMU: In QEMU:
@@ -73,11 +65,9 @@ c
and you now control the count. and you now control the count.
TODO: if I `-ex lx-symbols` to the `gdb` command, just like done for TODO: if I `-ex lx-symbols` to the `gdb` command, just like done for QEMU `-gdb`, the kernel oops. How to automate this step?
QEMU `-gdb`, the kernel oops. How to automate this step?
[[kdb]] ==== KDB
== KDB
If you modify `runqemu` to use: If you modify `runqemu` to use:
@@ -85,8 +75,7 @@ If you modify `runqemu` to use:
-append kgdboc=kbd -append kgdboc=kbd
.... ....
instead of `kgdboc=ttyS0,115200`, you enter a different debugging mode instead of `kgdboc=ttyS0,115200`, you enter a different debugging mode called KDB.
called KDB.
Usage: in QEMU: Usage: in QEMU:
@@ -110,9 +99,6 @@ And you are back in KDB. Now you can:
And you will break whenever `sys_write` is hit. And you will break whenever `sys_write` is hit.
The other KDB commands allow you to instruction steps, view memory, The other KDB commands allow you to instruction steps, view memory, registers and some higher level kernel runtime data.
registers and some higher level kernel runtime data.
But TODO I don't think you can see where you are in the kernel source But TODO I don't think you can see where you are in the kernel source code and line step as from GDB, since the kernel source is not available on guest (ah, if only debugging information supported full source).
code and line step as from GDB, since the kernel source is not available
on guest (ah, if only debugging information supported full source).

View File

@@ -1,8 +1,6 @@
[[kmod]] === kmod
= kmod
Multi-call executable that implements: `lsmod`, `insmod`, `rmmod`, and Multi-call executable that implements: `lsmod`, `insmod`, `rmmod`, and other tools on desktop distros such as Ubuntu 16.04, where e.g.:
other tools on desktop distros such as Ubuntu 16.04, where e.g.:
.... ....
ls -l /bin/lsmod ls -l /bin/lsmod
@@ -26,24 +24,19 @@ contains:
ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules
.... ....
BusyBox also implements its own version of those executables. There are BusyBox also implements its own version of those executables. There are some differences.
some differences.
Buildroot also has a kmod package, but we are not using it since Buildroot also has a kmod package, but we are not using it since BusyBox' version is good enough so far.
BusyBox' version is good enough so far.
This page will only describe features that differ from kmod to the This page will only describe features that differ from kmod to the BusyBox implementation.
BusyBox implementation.
Source code: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git Source code: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git
[[module-init-tools]] ==== module-init-tools
== module-init-tools
Name of a predecessor set of tools. Name of a predecessor set of tools.
[[modprobe]] ==== modprobe
== modprobe
Load module under different name to avoid conflicts: Load module under different name to avoid conflicts:

View File

@@ -1,8 +1,6 @@
[[maintainers]] === Maintainers
= Maintainers
[[how-to-update-the-linux-kernel]] ==== How to update the Linux kernel?
== How to update the Linux kernel?
.... ....
# Last point before out patches. # Last point before out patches.
@@ -30,29 +28,21 @@ git push
and update the README! and update the README!
During update all you kernel modules may break since the kernel API is During update all you kernel modules may break since the kernel API is not stable.
not stable.
They are usually trivial breaks of things moving around headers or to They are usually trivial breaks of things moving around headers or to sub-structs.
sub-structs.
The userland, however, should simply not break, as Linus enforces strict The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.
backwards compatibility of userland interfaces.
This backwards compatibility is just awesome, it makes getting and This backwards compatibility is just awesome, it makes getting and running the latest master painless.
running the latest master painless.
This also makes this repo the perfect setup to develop the Linux kernel. This also makes this repo the perfect setup to develop the Linux kernel.
[[how-to-downgrade-the-linux-kernel]] ==== How to downgrade the Linux kernel?
== How to downgrade the Linux kernel?
The kernel is not forward compatible, however, so downgrading the Linux The kernel is not forward compatible, however, so downgrading the Linux kernel requires downgrading the userland too to the latest Buildroot branch that supports it.
kernel requires downgrading the userland too to the latest Buildroot
branch that supports it.
The default Linux kernel version is bumped in Buildroot with commit The default Linux kernel version is bumped in Buildroot with commit messages of type:
messages of type:
.... ....
linux: bump default to version 4.9.6 linux: bump default to version 4.9.6
@@ -64,15 +54,11 @@ So you can try:
git log --grep 'linux: bump default to version' git log --grep 'linux: bump default to version'
.... ....
Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in `/linux/Config.in`.
`/linux/Config.in`.
You should then look up if there is a branch that supports that kernel. You should then look up if there is a branch that supports that kernel. Staying on branches is a good idea as they will get backports, in particular ones that fix the build as newer host versions come out.
Staying on branches is a good idea as they will get backports, in
particular ones that fix the build as newer host versions come out.
[[how-to-add-new-buildroot-options]] ==== How to add new Buildroot options?
== How to add new Buildroot options?
.... ....
cd buildroot/output.x86_64~ cd buildroot/output.x86_64~

View File

@@ -1,5 +1,4 @@
[[modprobe]] === modprobe
= modprobe
If you are feeling fancy, you can also insert modules with: If you are feeling fancy, you can also insert modules with:
@@ -9,8 +8,7 @@ lsmod
# dep and dep2 # dep and dep2
.... ....
This method also deals with module dependencies, which we almost don't This method also deals with module dependencies, which we almost don't use to make examples simpler:
use to make examples simpler:
* https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe * https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe
* https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe * https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe
@@ -40,8 +38,7 @@ so it is a bit risky.
ls /lib/modules/*/extra/ ls /lib/modules/*/extra/
.... ....
Kernel modules built from the Linux mainline tree with Kernel modules built from the Linux mainline tree with `CONFIG_SOME_MOD=m`, are automatically available with `modprobe`, e.g.:
`CONFIG_SOME_MOD=m`, are automatically available with `modprobe`, e.g.:
.... ....
modprobe dummy-irq modprobe dummy-irq

View File

@@ -1,11 +1,8 @@
[[other-architectures]] === Other architectures
= Other architectures
The portability of the kernel and toolchains is amazing: change an The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.
option and most things magically work on completely different hardware.
[[arm]] ==== arm
== arm
First build: First build:
@@ -24,14 +21,10 @@ Debug:
TODOs: TODOs:
* only managed to run in the terminal interface (but weirdly a blank * only managed to run in the terminal interface (but weirdly a blank QEMU window is still opened)
QEMU window is still opened) * GDB not connecting to KGDB. Possibly linked to `-serial stdio`. See also: https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
* GDB not connecting to KGDB. Possibly linked to `-serial stdio`. See
also:
https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
[[aarch64]] ==== aarch64
== aarch64
.... ....
./build -a aarch64 ./build -a aarch64
@@ -48,8 +41,7 @@ no module object found for ''
when you connect. `Ctrl + C` then `c` works though. when you connect. `Ctrl + C` then `c` works though.
* How to add devices to `-M virt` as we did for `-M versatilepb` * How to add devices to `-M virt` as we did for `-M versatilepb`
[[mips64]] ==== mips64
== mips64
.... ....
./build -a mips64 ./build -a mips64

2
qemu

Submodule qemu updated: 23bdb6f7ce...09fa182a4e

View File

@@ -1,5 +1,4 @@
[[qemu-user-mode]] === QEMU user mode
= QEMU user mode
This has nothing to do with the Linux kernel, but it is cool: This has nothing to do with the Linux kernel, but it is cool:
@@ -10,12 +9,9 @@ cd buildroot/output.arm~/target
qemu-arm -L . bin/ls qemu-arm -L . bin/ls
.... ....
This uses QEMU's user-mode emulation mode that allows us to run This uses QEMU's user-mode emulation mode that allows us to run cross-compiled userland programs directly on the host.
cross-compiled userland programs directly on the host.
The reason this is cool, is that `ls` is not statically compiled, but The reason this is cool, is that `ls` is not statically compiled, but since we have the Buildroot image, we are still able to find the shared linker and the shared library at the given path.
since we have the Buildroot image, we are still able to find the shared
linker and the shared library at the given path.
In other words, much cooler than: In other words, much cooler than:
@@ -24,20 +20,15 @@ arm-linux-gnueabi-gcc -o hello -static hello.c
qemu-arm hello qemu-arm hello
.... ....
It is also possible to compile QEMU user mode from source with It is also possible to compile QEMU user mode from source with `BR2_PACKAGE_HOST_QEMU_LINUX_USER_MODE=y`, but then your compilation will likely fail with:
`BR2_PACKAGE_HOST_QEMU_LINUX_USER_MODE=y`, but then your compilation
will likely fail with:
.... ....
package/qemu/qemu.mk:110: *** "Refusing to build qemu-user: target Linux version newer than host's.". Stop. package/qemu/qemu.mk:110: *** "Refusing to build qemu-user: target Linux version newer than host's.". Stop.
.... ....
since we are using a bleeding edge kernel, which is a sanity check in since we are using a bleeding edge kernel, which is a sanity check in the Buildroot QEMU package.
the Buildroot QEMU package.
Anyways, this warns us that the userland emulation will likely not be Anyways, this warns us that the userland emulation will likely not be reliable, which is good to know. TODO: where is it documented the host kernel must be as new as the target one?
reliable, which is good to know. TODO: where is it documented the host
kernel must be as new as the target one?
GDB step debugging is also possible with: GDB step debugging is also possible with:

View File

@@ -1,13 +1,7 @@
[[record-and-replay]] === Record and replay
= Record and replay
QEMU supports deterministic record and replay by saving external inputs, QEMU supports deterministic record and replay by saving external inputs, which would be awesome to understand the kernel, as you would be able to examine a single run as many times as you would like.
which would be awesome to understand the kernel, as you would be able to
examine a single run as many times as you would like.
Unfortunately it is not working in the current QEMU: Unfortunately it is not working in the current QEMU: https://stackoverflow.com/questions/46970215/how-to-use-qemus-deterministic-record-and-replay-feature-for-a-linux-kernel-boo
https://stackoverflow.com/questions/46970215/how-to-use-qemus-deterministic-record-and-replay-feature-for-a-linux-kernel-boo
Alternatively, https://github.com/mozilla/rr[`mozilla/rr`] claims it is Alternatively, https://github.com/mozilla/rr[`mozilla/rr`] claims it is able to run QEMU: but using it would require you to step through QEMU code itself. Likely doable, but do you really want to?
able to run QEMU: but using it would require you to step through QEMU
code itself. Likely doable, but do you really want to?

View File

@@ -1,26 +1,14 @@
[[run-on-host]] === Run on host
= Run on host
This method runs the kernel modules directly on your host computer This method runs the kernel modules directly on your host computer without a VM, and saves you the compilation time and disk usage of the virtual machine method.
without a VM, and saves you the compilation time and disk usage of the
virtual machine method.
It has however severe limitations, and you will soon see that the It has however severe limitations, and you will soon see that the compilation time and disk usage are well worth it:
compilation time and disk usage are well worth it:
* can't control which kernel version and build options to use. So some * can't control which kernel version and build options to use. So some of the modules will likely not compile because of kernel API changes, since https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681[the Linux kernel does not have a stable kernel module API].
of the modules will likely not compile because of kernel API changes,
since
https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681[the
Linux kernel does not have a stable kernel module API].
* bugs can easily break you system. E.g.: * bugs can easily break you system. E.g.:
** segfaults can trivially lead to a kernel crash, and require a reboot ** segfaults can trivially lead to a kernel crash, and require a reboot
** your disk could get erased. Yes, this can also happen with `sudo` ** your disk could get erased. Yes, this can also happen with `sudo` from userland. But you should not use `sudo` when developing newbie programs. And for the kernel you don't have the choice not to use `sudo`
from userland. But you should not use `sudo` when developing newbie ** even more subtle system corruption such as https://unix.stackexchange.com/questions/78858/cannot-remove-or-reinsert-kernel-module-after-error-while-inserting-it-without-r[not being able to rmmod]
programs. And for the kernel you don't have the choice not to use `sudo`
** even more subtle system corruption such as
https://unix.stackexchange.com/questions/78858/cannot-remove-or-reinsert-kernel-module-after-error-while-inserting-it-without-r[not
being able to rmmod]
* can't control which hardware is used, notably the CPU architecture * can't control which hardware is used, notably the CPU architecture
* can't step debug it with GDB easily * can't step debug it with GDB easily
@@ -31,17 +19,14 @@ cd kernel_module
./make-host.sh ./make-host.sh
.... ....
If the compilation of any of the C files fails because of kernel or If the compilation of any of the C files fails because of kernel or toolchain differences that we don't control on the host, just rename it to remove the `.c` extension and try again:
toolchain differences that we don't control on the host, just rename it
to remove the `.c` extension and try again:
.... ....
mv broken.c broken.c~ mv broken.c broken.c~
./build_host ./build_host
.... ....
Once you manage to compile, and have come to terms with the fact that Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:
this may blow up your host, try it out with:
.... ....
sudo insmod hello.ko sudo insmod hello.ko

7
snapshot.adoc Normal file
View File

@@ -0,0 +1,7 @@
=== Snapshot
QEMU allows us to take snapshots at any time through the monitor.
You can then restore CPU, memory and disk state back at any time.
Here's how: https://stackoverflow.com/questions/40227651/does-qemu-emulator-have-checkpoint-function/48724371#48724371

View File

@@ -1,5 +1,4 @@
[[x11]] === X11
= X11
Only tested successfully in `x86_64`. Only tested successfully in `x86_64`.
@@ -10,9 +9,7 @@ Build:
./run ./run
.... ....
We don't build X11 by default because it takes a considerable amount of We don't build X11 by default because it takes a considerable amount of time (~20%), and is not expected to be used by most users: you need to pass the `-x` flag to enable it.
time (~20%), and is not expected to be used by most users: you need to
pass the `-x` flag to enable it.
Inside QEMU: Inside QEMU:
@@ -22,14 +19,11 @@ startx
image:x11.png[image] image:x11.png[image]
More details: More details: https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
Not sure how well that graphics stack represents real systems, but if it Not sure how well that graphics stack represents real systems, but if it does it would be a good way to understand how it works.
does it would be a good way to understand how it works.
[[x11-arm]] ==== X11 ARM
== X11 ARM
On ARM, `startx` hangs at a message: On ARM, `startx` hangs at a message:
@@ -51,8 +45,5 @@ says:
A friend told me this but I haven't tried it yet: A friend told me this but I haven't tried it yet:
* `xf86-video-modesetting` is likely the missing ingredient, but it does * `xf86-video-modesetting` is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.
not seem possible to activate it from Buildroot currently without * `xf86-video-fbdev` should work as well, but we need to make sure fbdev is enabled, and maybe add some line to the `Xorg.conf`
patching things.
* `xf86-video-fbdev` should work as well, but we need to make sure fbdev
is enabled, and maybe add some line to the `Xorg.conf`