README.adoc 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  1. = Linux Kernel Module Cheat
  2. :idprefix:
  3. :idseparator: -
  4. :sectanchors:
  5. :sectlinks:
  6. :sectnumlevels: 6
  7. :sectnums:
  8. :toc: macro
  9. :toclevels: 6
  10. :toc-title:
  11. 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.
  12. toc::[]
  13. == Action
  14. === Getting started
  15. Reserve 12Gb of disk and run:
  16. ....
  17. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  18. cd linux-kernel-module-cheat
  19. ./configure && ./build && ./run
  20. ....
  21. The first build will take a while (https://stackoverflow.com/questions/10833672/buildroot-environment-with-host-toolchain[GCC], Linux kernel), e.g.:
  22. * 2 hours on a mid end 2012 laptop
  23. * 30 minutes on a high end 2017 desktop
  24. 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.
  25. After QEMU opens up, you can start playing with the kernel modules:
  26. ....
  27. root
  28. insmod /hello.ko
  29. insmod /hello2.ko
  30. rmmod hello
  31. rmmod hello2
  32. ....
  33. This should print to the screen:
  34. ....
  35. hello init
  36. hello2 init
  37. hello cleanup
  38. hello2 cleanup
  39. ....
  40. which are `printk` messages from `init` and `cleanup` methods of those modules.
  41. image:screenshot.png[image]
  42. All available modules can be found in the link:kernel_module/[`kernel_module` directory].
  43. ==== Module documentation
  44. ....
  45. head kernel_module/modulename.c
  46. ....
  47. Many of the modules have userland test scripts / executables with the same name as the module, e.g. form inside the guest:
  48. ....
  49. /modulename.sh
  50. /modulename.out
  51. ....
  52. The sources of those tests will further clarify what the corresponding kernel modules does. To find them on the host, do a quick:
  53. ....
  54. git ls-files | grep modulename
  55. ....
  56. ==== Rebuild
  57. If you make changes to the kernel modules or most configurations tracked on this repository, you can just use again:
  58. ....
  59. ./build
  60. ./run
  61. ....
  62. and the modified files will be rebuilt.
  63. If you change any package besides `kernel_module`, you must also request those packages to be reconfigured or rebuilt with extra targets, e.g.:
  64. ....
  65. ./build -t linux-reconfigure -t host-qemu-reconfigure
  66. ....
  67. Those aren't turned on by default because they take quite a few seconds.
  68. Linux and QEMU rebuilds are so common that we have dedicated shortcut flags for them:
  69. ....
  70. ./build -l -q
  71. ....
  72. ==== Clean the build
  73. You did something crazy, and nothing seems to work anymore?
  74. All builds are stored under `buildroot/`,
  75. The most coarse thing you can do is:
  76. ....
  77. cd buildroot
  78. git checkout -- .
  79. git clean -xdf .
  80. ....
  81. To only nuke one architecture, do:
  82. ....
  83. rm -rf buildroot/output.x86_64~
  84. ....
  85. Only nuke one one package:
  86. ....
  87. rm -rf buildroot/output.x86_64~/build/host-qemu-custom
  88. ./build -q
  89. ....
  90. This is sometimes necessary when changing the version of the submodules, and then builds fail. We should try to understand why and report bugs.
  91. ==== Filesystem persistency
  92. The root filesystem is persistent across:
  93. ....
  94. ./run
  95. date >f
  96. sync
  97. poweroff
  98. ....
  99. then:
  100. ....
  101. ./run
  102. cat f
  103. ....
  104. This is particularly useful to re-run shell commands from the history of a previous session with `Ctrl + R`.
  105. However, when you do:
  106. ....
  107. ./build
  108. ....
  109. the disk image gets overwritten by a fresh filesystem and you lose all changes.
  110. 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.
  111. ==== Message control
  112. 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:
  113. ....
  114. dmesg -n 1
  115. ....
  116. See also: https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
  117. You can scroll up a bit on the default TTY with:
  118. ....
  119. Shift + PgUp
  120. ....
  121. but I never managed to increase that buffer:
  122. * https://askubuntu.com/questions/709697/how-to-increase-scrollback-lines-in-ubuntu14-04-2-server-edition
  123. * https://unix.stackexchange.com/questions/346018/how-to-increase-the-scrollback-buffer-size-for-tty
  124. The superior alternative is to use text mode or a telnet connection.
  125. ==== Text mode
  126. Show serial console directly on the current terminal, without opening a QEMU window:
  127. ....
  128. ./run -n
  129. ....
  130. To exit, just do a regular:
  131. ....
  132. poweroff
  133. ....
  134. This mode is very useful to:
  135. * 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
  136. * copy and paste commands and stdout output to / from host
  137. * have a large scroll buffer, and be able to search it, e.g. by using GNU `screen` on host
  138. 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
  139. ....
  140. Ctrl-C X
  141. ....
  142. or:
  143. ....
  144. Ctrl-C A
  145. quit
  146. ....
  147. or on host:
  148. ....
  149. ./qemumonitor
  150. quit
  151. ....
  152. or:
  153. ....
  154. echo quit | ./qemumonitor
  155. ....
  156. See also:
  157. * http://stackoverflow.com/questions/14165158/how-to-switch-to-qemu-monitor-console-when-running-with-curses
  158. * https://superuser.com/questions/1087859/how-to-quit-qemu-monitor
  159. * https://superuser.com/questions/488263/problems-switching-to-qemu-control-panel-with-nographics
  160. * https://superuser.com/questions/1087859/how-to-quit-the-qemu-monitor-when-not-using-a-gui/1211516#1211516
  161. Limitations:
  162. * TODO: Ctrl + C kills the emulator for some setups (TODO which what exactly?), and not sent to guest processes. See:
  163. ** https://github.com/cloudius-systems/osv/issues/49
  164. ** https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-in-qemu
  165. +
  166. This is however fortunate when running QEMU with GDB, as the Ctrl + C reaches GDB and breaks.
  167. * 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.
  168. ==== Automatic startup commands
  169. When debugging a module, it becomes tedious to wait for build and re-type:
  170. ....
  171. root
  172. /modulename.sh
  173. ....
  174. every time.
  175. Instead, you can either run them from a minimal init:
  176. ....
  177. ./run -e 'init=/eval.sh - lkmc_eval="insmod /hello.ko;/poweroff.out"' -n
  178. ....
  179. or run them at the end of the BusyBox init, which does things like setting up networking:
  180. ....
  181. ./run -e '- lkmc_eval="insmod /hello.ko;wget -S google.com;poweroff.out;"'
  182. ....
  183. or add them to a new `init.d` entry:
  184. ....
  185. cp rootfs_overlay/etc/init.d/S98 rootfs_overlay/etc/init.d/S99
  186. vim S99
  187. ./build
  188. ./run
  189. ....
  190. and they will be run automatically before the login prompt.
  191. `S99` is a git tracked convenience symlink to the gitignored `rootfs_overlay/etc/init.d/S99`
  192. 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`.
  193. ==== Kernel version
  194. We try to use the latest possible kernel major release version.
  195. In QEMU:
  196. ....
  197. cat /proc/version
  198. ....
  199. or in the source:
  200. ....
  201. cd linux
  202. git log | grep -E ' Linux [0-9]+\.' | head
  203. ....
  204. Build configuration can be observed in guest with:
  205. ....
  206. zcat /proc/config.gz
  207. ....
  208. or on host:
  209. ....
  210. cat buildroot/output.*~/build/linux-custom/.config
  211. ....
  212. ==== Kernel boot command line arguments
  213. Bootloaders can pass a string as input to the Linux kernel when it is booting to control its behaviour, much like the `execve` system call does to userland processes.
  214. This allows us to control the behaviour of the kernel without rebuilding anything.
  215. With QEMU, QEMU itself acts as the bootloader, and provides the `-append` option and we expose it through `./run -e`, e.g.:
  216. ....
  217. ./run -e 'foo bar'
  218. ....
  219. Then inside the host, you can check which options were given with:
  220. ....
  221. cat /proc/cmdline
  222. ....
  223. They are also printed at the beginning of the boot message:
  224. ....
  225. dmesg | grep "Command line"
  226. ....
  227. See also:
  228. * https://unix.stackexchange.com/questions/48601/how-to-display-the-linux-kernel-command-line-parameters-given-for-the-current-bo
  229. * https://askubuntu.com/questions/32654/how-do-i-find-the-boot-parameters-used-by-the-running-kernel
  230. The arguments are documented in the kernel documentation: https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  231. When dealing with real boards, extra command line options are provided on some magic bootloader configuration file, e.g.:
  232. * GRUB configuration files: https://askubuntu.com/questions/19486/how-do-i-add-a-kernel-boot-parameter
  233. * Raspberry pi `/boot/cmdline.txt` on a magic partition: https://raspberrypi.stackexchange.com/questions/14839/how-to-change-the-kernel-commandline-for-archlinuxarm-on-raspberry-pi-effectly
  234. ==== QEMU GUI is unresponsive
  235. 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.
  236. We have not managed to track this problem down yet, but the following workaround always works:
  237. ....
  238. Ctrl + Shift + U
  239. Ctrl + C
  240. root
  241. ....
  242. This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.
  243. Using text mode is another workaround if you don't need GUI features.
  244. ==== Debug QEMU
  245. When you start interacting with QEMU hardware, it is useful to see what is going on inside of QEMU itself.
  246. This is of course trivial since QEMU is just an userland program on the host, but we make it a bit easier with:
  247. ....
  248. ./run -q
  249. ....
  250. Then you could:
  251. ....
  252. b edu_mmio_read
  253. c
  254. ....
  255. And in QEMU:
  256. ....
  257. /pci.sh
  258. ....
  259. 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.
  260. 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.
  261. [[gdb]]
  262. === GDB step debugging
  263. To GDB step debug the Linux kernel, first run:
  264. ....
  265. ./run -d
  266. ....
  267. If you want to break immediately at a symbol, e.g. `start_kernel` of the boot sequence, run on another shell:
  268. ....
  269. ./rungdb start_kernel
  270. ....
  271. Now QEMU will stop there, and you can use the normal GDB commands:
  272. ....
  273. l
  274. n
  275. c
  276. ....
  277. To skip the boot, run just:
  278. ....
  279. ./rungdb
  280. ....
  281. and when you want to break, do `Ctrl + C` from GDB.
  282. To have some fun, you can first run inside QEMU:
  283. ....
  284. /count.sh
  285. ....
  286. which counts to infinity to stdout, and then in GDB:
  287. ....
  288. Ctrl + C
  289. break sys_write
  290. continue
  291. continue
  292. continue
  293. ....
  294. And you now control the counting from GDB.
  295. See also:
  296. * http://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642
  297. * http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607
  298. `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.
  299. ==== Kernel module debugging
  300. Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.
  301. So we cannot set the breakpoints before `insmod`.
  302. However, the Linux kernel GDB scripts offer the `lx-symbols` command, which takes care of that beautifully for us:
  303. ....
  304. ./run -d
  305. ./rungdb
  306. ....
  307. In QEMU:
  308. ....
  309. insmod /fops.ko
  310. ....
  311. In GDB, hit `Ctrl + C`, and note how it says:
  312. ....
  313. scanning for modules in ../kernel_module-1.0/
  314. loading @0xffffffffa0000000: ../kernel_module-1.0//fops.ko
  315. ....
  316. That's `lx-symbols` working! Now simply:
  317. ....
  318. b fop_write
  319. c
  320. ....
  321. In QEMU:
  322. ....
  323. printf a >/sys/kernel/debug/lkmc_fops/f
  324. ....
  325. and GDB now breaks at our `fop_write` function!
  326. Just don't forget to remove your breakpoints after `rmmod`, or they will point to stale memory locations.
  327. TODO: why does `break work_func` for `insmod kthread.ko` not break the first time I `insmod`, but breaks the second time?
  328. See also: http://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
  329. ===== Bypassing lx-symbols
  330. Useless, but a good way to show how hardcore you are. From inside QEMU:
  331. ....
  332. insmod /fops.ko
  333. cat /proc/modules
  334. ....
  335. This will give a line of form:
  336. ....
  337. fops 2327 0 - Live 0xfffffffa00000000
  338. ....
  339. And then tell GDB where the module was loaded with:
  340. ....
  341. Ctrl + C
  342. add-symbol-file ../kernel_module-1.0/fops.ko 0xfffffffa00000000
  343. ....
  344. ==== Debug kernel early boot
  345. TODO: why can't we break at early startup stuff such as:
  346. ....
  347. ./rungdb extract_kernel
  348. ./rungdb main
  349. ....
  350. See also: https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
  351. ==== GDB call
  352. GDB can call functions as explained at: https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb
  353. However this is failing for us:
  354. * some symbols are not visible to `call` even though `b` sees them
  355. * for those that are, `call` fails with an E14 error
  356. E.g.: if we break on `sys_write` on `/count.sh`:
  357. ....
  358. >>> call printk(0, "asdf")
  359. Could not fetch register "orig_rax"; remote failure reply 'E14'
  360. >>> b printk
  361. Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
  362. >>> call fdget_pos(fd)
  363. No symbol "fdget_pos" in current context.
  364. >>> b fdget_pos
  365. Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
  366. >>>
  367. ....
  368. even though `fdget_pos` is the first thing `sys_write` does:
  369. ....
  370. 581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
  371. 582 size_t, count)
  372. 583 {
  373. 584 struct fd f = fdget_pos(fd);
  374. ....
  375. See also: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/19
  376. === KGDB
  377. KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.
  378. It is useless with QEMU since we already have full system visibility with `-gdb`, but this is a good way to learn it.
  379. 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.
  380. Usage:
  381. ....
  382. ./run -k
  383. ./rungdb -k
  384. ....
  385. In GDB:
  386. ....
  387. c
  388. ....
  389. In QEMU:
  390. ....
  391. /count.sh &
  392. /kgdb.sh
  393. ....
  394. In GDB:
  395. ....
  396. b sys_write
  397. c
  398. c
  399. c
  400. c
  401. ....
  402. And now you can count from GDB!
  403. 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.
  404. See also:
  405. * https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl
  406. * https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715
  407. ==== KGDB kernel modules
  408. In QEMU:
  409. ....
  410. /kgdb-mod.sh
  411. ....
  412. In GDB:
  413. ....
  414. lx-symbols ../kernel_module-1.0/
  415. b fop_write
  416. c
  417. c
  418. c
  419. ....
  420. and you now control the count.
  421. TODO: if I `-ex lx-symbols` to the `gdb` command, just like done for QEMU `-gdb`, the kernel oops. How to automate this step?
  422. ==== KDB
  423. If you modify `runqemu` to use:
  424. ....
  425. -append kgdboc=kbd
  426. ....
  427. instead of `kgdboc=ttyS0,115200`, you enter a different debugging mode called KDB.
  428. Usage: in QEMU:
  429. ....
  430. [0]kdb> go
  431. ....
  432. Boot finishes, then:
  433. ....
  434. /kgdb.sh
  435. ....
  436. And you are back in KDB. Now you can:
  437. ....
  438. [0]kdb> help
  439. [0]kdb> bp sys_write
  440. [0]kdb> go
  441. ....
  442. And you will break whenever `sys_write` is hit.
  443. The other KDB commands allow you to instruction steps, view memory, registers and some higher level kernel runtime data.
  444. 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).
  445. === gdbserver
  446. Step debug userland processes to understand how they are talking to the kernel.
  447. In guest:
  448. ....
  449. /gdbserver.sh /myinsmod.out /hello.ko
  450. ....
  451. In host:
  452. ....
  453. ./rungdbserver kernel_module-1.0/user/myinsmod.out
  454. ....
  455. You can find the executable with:
  456. ....
  457. find buildroot/output.x86_64~/build -name myinsmod.out
  458. ....
  459. TODO: automate the path finding:
  460. * 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.
  461. * `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.
  462. +
  463. E.g. `pciutils` has for `lspci`:
  464. +
  465. ....
  466. define PCIUTILS_INSTALL_STAGING_CMDS
  467. $(TARGET_MAKE_ENV) $(MAKE1) -C $(@D) $(PCIUTILS_MAKE_OPTS) \
  468. PREFIX=$(STAGING_DIR)/usr SBINDIR=$(STAGING_DIR)/usr/bin \
  469. install install-lib install-pcilib
  470. endef
  471. ....
  472. +
  473. and the docs describe the `*_INSTALL_STAGING` per package config, which is normally set for shared library packages.
  474. +
  475. Feature request: https://bugs.busybox.net/show_bug.cgi?id=10386
  476. An implementation overview can be found at: https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-mips-elf-with-qemu-toolchain/16214#16214
  477. ==== gdbserver different archs
  478. As usual, different archs work with:
  479. ....
  480. ./rungdbserver -a arm kernel_module-1.0/user/myinsmod.out
  481. ....
  482. ==== gdbserver BusyBox
  483. BusyBox executables are all symlinks, so if you do on guest:
  484. ....
  485. /gdbserver.sh ls
  486. ....
  487. on host you need:
  488. ....
  489. ./rungdbserver busybox-1.26.2/busybox
  490. ....
  491. ==== gdbserver shared libraries
  492. Our setup gives you the rare opportunity to step debug libc and other system libraries e.g. with:
  493. ....
  494. b open
  495. c
  496. ....
  497. Or simply by stepping into calls:
  498. ....
  499. s
  500. ....
  501. This is made possible by the GDB command:
  502. ....
  503. set sysroot ${buildroot_out_dir}/staging
  504. ....
  505. which automatically finds unstripped shared libraries on the host for us.
  506. See also: https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
  507. ==== Debug userland process without gdbserver
  508. QEMU `-gdb` GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.
  509. * https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel
  510. * https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb
  511. 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:
  512. * the kernel might switch context to another process, and you would enter "garbage"
  513. * TODO step into shared libraries. If I attempt to load them explicitly:
  514. +
  515. ....
  516. (gdb) sharedlibrary ../../staging/lib/libc.so.0
  517. No loaded shared libraries match the pattern `../../staging/lib/libc.so.0'.
  518. ....
  519. +
  520. since GDB does not know that libc is loaded.
  521. Custom init process:
  522. * Shell 1:
  523. +
  524. ....
  525. ./run -d -e 'init=/sleep_forever.out' -n
  526. ....
  527. * Shell 2:
  528. +
  529. ....
  530. ./rungdb-user kernel_module-1.0/user/sleep_forever.out main
  531. ....
  532. BusyBox custom init process:
  533. * Shell 1:
  534. +
  535. ....
  536. ./run -d -e 'init=/bin/ls' -n
  537. ....
  538. * Shell 2:
  539. +
  540. ....
  541. ./rungdb-user -h busybox-1.26.2/busybox ls_main
  542. ....
  543. This follows BusyBox' convention of calling the main for each executable as `<exec>_main` since the `busybox` executable has many "mains".
  544. BusyBox default init process:
  545. * Shell 1:
  546. +
  547. ....
  548. ./run -d -n
  549. ....
  550. * Shell 2:
  551. +
  552. ....
  553. ./rungdb-user -h busybox-1.26.2/busybox init_main
  554. ....
  555. This cannot be debugged in another way without modifying the source, or `/sbin/init` exits early with:
  556. ....
  557. "must be run as PID 1"
  558. ....
  559. Non-init process:
  560. * Shell 1
  561. +
  562. ....
  563. ./run -d -n
  564. ....
  565. * Shell 2
  566. +
  567. ....
  568. ./rungdb-user kernel_module-1.0/user/sleep_forever.out
  569. Ctrl + C
  570. b main
  571. continue
  572. ....
  573. * Shell 1
  574. +
  575. ....
  576. /sleep_forever.out
  577. ....
  578. This is of least reliable setup as there might be other processes that use the given virtual address.
  579. === Other architectures
  580. The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.
  581. ==== arm
  582. First build:
  583. ....
  584. ./build -a arm
  585. ./run -a arm
  586. ....
  587. Debug:
  588. ....
  589. ./run -a arm -d
  590. # On another terminal.
  591. ./rungdb -a arm
  592. ....
  593. TODOs:
  594. * only managed to run in the terminal interface (but weirdly a blank QEMU window is still opened)
  595. * GDB not connecting to KGDB. Possibly linked to `-serial stdio`. See also: https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
  596. * `/poweroff.out` does not exit QEMU, the terminal just hangs: https://stackoverflow.com/questions/31990487/how-to-cleanly-exit-qemu-after-executing-bare-metal-program-without-user-interve A blunt resolution is:
  597. +
  598. ....
  599. pkill qemu
  600. ....
  601. ==== aarch64
  602. ....
  603. ./build -a aarch64
  604. ....
  605. As usual, we use Buildroot's recommended QEMU setup QEMU `aarch64` setup:
  606. * https://github.com/buildroot/buildroot/blob/2017.08/board/qemu/aarch64-virt/readme.txt
  607. * https://github.com/buildroot/buildroot/blob/2017.08/configs/qemu_aarch64_virt_defconfig
  608. This makes aarch64 a bit different from `arm`:
  609. * uses `-M virt`. https://wiki.qemu.org/Documentation/Platforms/ARM explains:
  610. +
  611. ____
  612. Most of the machines QEMU supports have annoying limitations (small amount of RAM, no PCI or other hard disk, etc) which are there because that's what the real hardware is like. If you don't care about reproducing the idiosyncrasies of a particular bit of hardware, the best choice today is the "virt" machine.
  613. ____
  614. +
  615. `-M virt` has some limitations, e.g. I could not pass `-drive if=scsi` as for `arm`, and so <<Snapshot>> fails.
  616. +
  617. * uses <<initramfs>>, so thre is no filesystem persistency.
  618. So, as long as you keep those points in mind, our `-a aarch64` offers an interesting different setup to play with.
  619. TODOs:
  620. * <<gdb>> appears to be stuck on an infinite loop:
  621. +
  622. ....
  623. no module object found for ''
  624. ....
  625. ==== mips64
  626. ....
  627. ./build -a mips64
  628. ....
  629. Keep in mind that MIPS has the worst support our architectures due to the smaller community. Patches welcome as usual.
  630. TODOs:
  631. * networking is not working. See also:
  632. ** https://stackoverflow.com/questions/21496449/networking-is-not-working-on-qemu-guest-malta-mips
  633. ** https://unix.stackexchange.com/questions/208266/setting-up-qemu-and-mipsel-networking-trouble
  634. ** https://unix.stackexchange.com/questions/354127/qemu-mips-and-debian
  635. * <<gdb>> does not work properly, does not find `start_kernel`
  636. === init
  637. When the Linux kernel finishes booting, it runs an executable as the first and only userland process.
  638. The default path is `/init`, but we an set a custom one with the `init=` kernel command line argument.
  639. This process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).
  640. This typically means reading some configuration files (e.g. `/etc/initrc`) and forking a bunch of userland executables based on those files.
  641. systemd is a "popular" `/init` implementation for desktop distros as of 2017.
  642. BusyBox provides its own minimalistic init implementation which Buildroot uses by default.
  643. ==== Custom init
  644. Is the default BusyBox `/init` too bloated for you, minimalism freak?
  645. No problem, just use the `init` kernel boot parameter:
  646. ....
  647. ./run -e 'init=/sleep_forever.out'
  648. ....
  649. Remember that shell scripts can also be used for `init` https://unix.stackexchange.com/questions/174062/init-as-a-shell-script/395375#395375:
  650. ....
  651. ./run -e 'init=/count.sh'
  652. ....
  653. Also remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:
  654. * run forever in a loop or long sleep
  655. * `poweroff` the machine
  656. ==== Disable networking
  657. 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.
  658. To disable networking, use:
  659. ....
  660. ./build -p -n
  661. ....
  662. To restore it, run:
  663. ....
  664. ./build -t initscripts-reconfigure
  665. ....
  666. ==== The init environment
  667. The docs make it clear https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  668. ____
  669. The kernel parses parameters from the kernel command line up to “–”; if it doesn’t recognize a parameter and it doesn’t contain a ‘.’, the parameter gets passed to init: parameters with ‘=’ go into init’s environment, others are passed as command line arguments to init. Everything after “–” is passed as an argument to init.
  670. ____
  671. And you can try it out with:
  672. ....
  673. ./run -e 'init=/init_env_poweroff.sh - asdf=qwer zxcv' -n
  674. ....
  675. === modprobe
  676. If you are feeling fancy, you can also insert modules with:
  677. ....
  678. modprobe dep2
  679. lsmod
  680. # dep and dep2
  681. ....
  682. This method also deals with module dependencies, which we almost don't use to make examples simpler:
  683. * https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe
  684. * https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe
  685. Removal also removes required modules that have zero usage count:
  686. ....
  687. modprobe -r dep2
  688. lsmod
  689. # Nothing.
  690. ....
  691. but it can't know if you actually insmodded them separately or not:
  692. ....
  693. modprobe dep
  694. modprobe dep2
  695. modprobe -r dep2
  696. # Nothing.
  697. ....
  698. so it is a bit risky.
  699. `modprobe` searches for modules under:
  700. ....
  701. ls /lib/modules/*/extra/
  702. ....
  703. Kernel modules built from the Linux mainline tree with `CONFIG_SOME_MOD=m`, are automatically available with `modprobe`, e.g.:
  704. ....
  705. modprobe dummy-irq
  706. ....
  707. === X11
  708. Only tested successfully in `x86_64`.
  709. Build:
  710. ....
  711. ./build -x
  712. ./run
  713. ....
  714. 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.
  715. Inside QEMU:
  716. ....
  717. startx
  718. ....
  719. image:x11.png[image]
  720. More details: https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
  721. 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.
  722. ==== X11 ARM
  723. On ARM, `startx` hangs at a message:
  724. ....
  725. vgaarb: this pci device is not a vga device
  726. ....
  727. and nothing shows on the screen, and:
  728. ....
  729. grep EE /var/log/Xorg.0.log
  730. ....
  731. says:
  732. ....
  733. (EE) Failed to load module "modesetting" (module does not exist, 0)
  734. ....
  735. A friend told me this but I haven't tried it yet:
  736. * `xf86-video-modesetting` is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.
  737. * `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`
  738. === Count boot instructions
  739. * https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take
  740. * https://github.com/cirosantilli/chat/issues/31
  741. * https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  742. * `qemu/docs/tracing.txt` and `qemu/docs/replay.txt`
  743. * https://stackoverflow.com/questions/39149446/how-to-use-qemus-simple-trace-backend/46497873#46497873
  744. Best attempt so far:
  745. ....
  746. time ./run -n -e 'init=/poweroff.out' -- -trace exec_tb,file=trace
  747. time ./qemu/scripts/simpletrace.py buildroot/output.x86_64~/build/host-qemu-custom/trace-events-all trace >trace.txt
  748. wc -l trace.txt
  749. sed '/0x1000000/q' trace.txt >trace-boot.txt
  750. wc -l trace-boot.txt
  751. ....
  752. Notes:
  753. * `-n` is a good idea to reduce the chances that you send unwanted non-deterministic mouse or keyboard clicks to the VM.
  754. * `-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.
  755. +
  756. 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.
  757. +
  758. 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`.
  759. * `0x1000000` is the address where QEMU puts the Linux kernel at with `-kernel` in x86.
  760. +
  761. It can be found from:
  762. +
  763. ....
  764. readelf -e buildroot/output.x86_64~/build/linux-*/vmlinux | grep Entry
  765. ....
  766. +
  767. TODO confirm further. If I try to break there with:
  768. +
  769. ....
  770. ./rungdb *0x1000000
  771. ....
  772. +
  773. 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:
  774. +
  775. ....
  776. ./rungdb extract_kernel
  777. ....
  778. +
  779. It only appears once on every log I've seen so far, checked with `grep 0x1000000 trace.txt`
  780. +
  781. 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.
  782. * 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:
  783. +
  784. ....
  785. ./rungdb-user kernel_module-1.0/user/poweroff.out main
  786. ....
  787. +
  788. And get that from the traces, e.g. if the address is `4003a0`, then we search:
  789. +
  790. ....
  791. grep -n 4003a0 trace.txt
  792. ....
  793. +
  794. 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.
  795. This works because we have already done the following with QEMU:
  796. * `./configure --enable-trace-backends=simple`. This logs in a binary format to the trace file.
  797. +
  798. It makes 3x execution faster than the default trace backend which logs human readable data to stdout.
  799. +
  800. 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.
  801. * patch QEMU source to remove the `disable` from `exec_tb` in the `trace-events`. See also: https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  802. Possible improvements:
  803. * to disable networking. Is replacing `init` enough?
  804. ** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled
  805. ** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015
  806. +
  807. `CONFIG_NET=n` did not significantly reduce instruction, so maybe replacing `init` is enough.
  808. * logging with the default backend `log` greatly slows down the CPU, and in particular leads to this during kernel boot:
  809. +
  810. ....
  811. All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
  812. swapper/0 R running task 0 1 0 0x00000008
  813. ffff880007c03ef8 ffffffff8107aa5d ffff880007c16b40 ffffffff81a3b100
  814. ffff880007c03f60 ffffffff810a41d1 0000000000000000 0000000007c03f20
  815. fffffffffffffedc 0000000000000004 fffffffffffffedc ffffffff00000000
  816. Call Trace:
  817. <IRQ> [<ffffffff8107aa5d>] sched_show_task+0xcd/0x130
  818. [<ffffffff810a41d1>] rcu_check_callbacks+0x871/0x880
  819. [<ffffffff810a799f>] update_process_times+0x2f/0x60
  820. ....
  821. +
  822. in which the boot appears to hang for a considerable time.
  823. * Confirm that the kernel enters at `0x1000000`, or where it enters. Once we have this, we can exclude what comes before in the BIOS.
  824. === GEM5
  825. ==== GEM5 Introduction
  826. GEM5 is a system simulator, much like QEMU: http://gem5.org/
  827. Vs QEMU:
  828. * 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:
  829. ** do much more realistic performance benchmarking with it, which makes absolutely no sense in QEMU, which is purely functional
  830. ** 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.
  831. +
  832. 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.
  833. +
  834. 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.
  835. * disadvantage: slower than QEMU by TODO 10x?
  836. +
  837. This also implies that the user base is much smaller, since no Android devs.
  838. +
  839. 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:
  840. ** the documentation is more scarce
  841. ** it takes longer to support new hardware features
  842. ==== GEM5 ARM
  843. ....
  844. ./configure && ./build -a arm -g
  845. ./rungem5 -a arm
  846. ....
  847. On another shell:
  848. ....
  849. ./rungem5-shell
  850. ....
  851. ===== GEM5 Kernel command line arguments
  852. E.g., to add `printk.time=y`, run:
  853. ....
  854. ./rungem5 -a arm -- --command-line='earlyprintk=pl011,0x1c090000 console=ttyAMA0 lpj=19988480 norandmaps rw loglevel=8 mem=512MB root=/dev/sda printk.time=y'
  855. ....
  856. When you use `--command-line=`, it overrides default command lines, which are required to boot properly.
  857. So if you pass just `--command-line='printk.time=y'`, it removes the required options, and boot fails.
  858. An easy way to find the other options is to to an initial boot:
  859. ....
  860. ./rungem5 -a arm
  861. ....
  862. and then look at the line of the linux kernel that starts with
  863. ....
  864. Kernel command line:
  865. ....
  866. 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 :-(
  867. ===== QEMU with GEM5 kernel configuration
  868. TODO: QEMU did not work with the GEM5 kernel configurations.
  869. To test this, hack up `run` to use the `buildroot/output.arm-gem5~` directory, and then run:
  870. ....
  871. ./run -a arm
  872. ....
  873. Now QEMU hangs at:
  874. ....
  875. audio: Could not init `oss' audio driver
  876. ....
  877. and the display shows:
  878. ....
  879. Guest has not initialized the display (yet).
  880. ....
  881. ===== GEM5 with QEMU kernel configuration
  882. Test it out with:
  883. ....
  884. ./rungem5 -a arm
  885. ....
  886. TODO hangs at:
  887. ....
  888. **** REAL SIMULATION ****
  889. warn: Existing EnergyCtrl, but no enabled DVFSHandler found.
  890. info: Entering event queue @ 0. Starting simulation...
  891. 1614868500: system.terminal: attach terminal 0
  892. ....
  893. and the `telnet` at:
  894. ....
  895. 2017-12-28-11-59-51@ciro@ciro-p51$ ./rungem5-shell
  896. Trying 127.0.0.1...
  897. Connected to localhost.
  898. Escape character is '^]'.
  899. ==== m5 slave terminal: Terminal 0 ====
  900. ....
  901. I have also tried to copy the exact same kernel command line options used by QEMU, but nothing changed.
  902. ===== GEM5 checkpoint
  903. Analogous to QEMU's <<snapshot>>.
  904. Documentation: http://gem5.org/Checkpoints
  905. ....
  906. ./rungem5 -a arm
  907. ....
  908. In guest, wait for the boot to end and run:
  909. ....
  910. /m5 checkpoint
  911. ....
  912. To restore the checkpoint, kill the VM and run:
  913. ....
  914. ./rungem5 -a arm -- -r 1
  915. ....
  916. Let's create a second checkpoint to see how it works, in guest:
  917. ....
  918. date >f
  919. /m5 checkpoint
  920. ....
  921. Kill the VM, and try it out:
  922. ....
  923. ./rungem5 -a arm -- -r 2
  924. ....
  925. and now in the guest:
  926. ....
  927. cat f
  928. ....
  929. contains the `date`. The file `f` wouldn't exist had we used the first checkpoint with `-r 1`.
  930. Internals:
  931. - the checkpoints are stored under `m5out/cpt.*`
  932. - `m5` is a guest utility present inside the GEM5 tree which we cross-compiled and installed into the guest
  933. ==== GEM5 x86
  934. TODO didn't get it working yet.
  935. Related threads:
  936. * https://www.mail-archive.com/gem5-users@gem5.org/msg11384.html
  937. * https://stackoverflow.com/questions/37906425/booting-gem5-x86-ubuntu-full-system-simulation
  938. * http://www.lowepower.com/jason/creating-disk-images-for-gem5.html claims to have a working config for x86_64 kernel 4.8.13
  939. ===== GEM5 x86 best attempt
  940. ....
  941. ./configure && ./build -a x86_64-gem5
  942. ./rungem5 -a x86_64-gem5
  943. ....
  944. telnet:
  945. ....
  946. i8042: PNP: No PS/2 controller found.
  947. i8042: Probing ports directly.
  948. Connection closed by foreign host.
  949. ....
  950. stdout:
  951. ....
  952. panic: Data written for unrecognized command 0xd1
  953. Memory Usage: 1235908 KBytes
  954. Program aborted at tick 427627410500
  955. ....
  956. 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..
  957. 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:
  958. ....
  959. WriteOutputPort = 0xD1,
  960. ....
  961. 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.
  962. This byte is documented at http://wiki.osdev.org/%228042%22_PS/2_Controller, as usual :-)
  963. There are also a bunch of `i8042` kernel CLI options, I tweaked all of them but nothing.
  964. ===== GDM5 x86 working baseline with magic image
  965. Working x86 with the pre-built magic image with an ancient 2.6.22.9 kernel starting point:
  966. ....
  967. sudo mkdir -p /dist/m5/system
  968. sudo chmod 777 /dist/m5/system
  969. cd /dist/m5/system
  970. # Backed up at:
  971. # https://github.com/cirosantilli/media/releases/tag/gem5
  972. wget http://www.gem5.org/dist/current/x86/x86-system.tar.bz2
  973. tar xvf x86-system.tar.bz2
  974. cd x86-system
  975. dd if=/dev/zero of=disks/linux-bigswap2.img bs=1024 count=65536
  976. mkswap disks/linux-bigswap2.img
  977. cd ..
  978. git clone https://gem5.googlesource.com/public/gem5
  979. cd gem5
  980. git checkout da79d6c6cde0fbe5473ce868c9be4771160a003b
  981. scons -j$(nproc) build/X86/gem5.opt
  982. # That old blob has wrong filenames.
  983. ./build/X86/gem5.opt \
  984. -d /tmp/output \
  985. --disk-image=/dist/m5/system/disks/linux-x86.img \
  986. --kernel=/dist/m5/system/binaries/x86_64-vmlinux-2.6.22.9 \
  987. configs/example/fs.py
  988. ....
  989. On another shell:
  990. ....
  991. telnet localhost 3456
  992. ....
  993. ===== GEM5 unmodified Buildroot images 2
  994. bzImage fails, so we always try with vmlinux obtained from inside build/.
  995. rootfs.ext2 and vmlinux from 670366caaded57d318b6dbef34e863e3b30f7f29ails as:
  996. Fails as:
  997. ....
  998. Global frequency set at 1000000000000 ticks per second
  999. warn: DRAM device capacity (8192 Mbytes) does not match the address range assigned (512 Mbytes)
  1000. info: kernel located at: /data/git/linux-kernel-module-cheat/buildroot/output.x86_64~/build/linux-custom/vmlinux
  1001. Listening for com_1 connection on port 3456
  1002. 0: rtc: Real-time clock set to Sun Jan 1 00:00:00 2012
  1003. 0: system.remote_gdb.listener: listening for remote gdb #0 on port 7000
  1004. warn: Reading current count from inactive timer.
  1005. **** REAL SIMULATION ****
  1006. info: Entering event queue @ 0. Starting simulation...
  1007. warn: instruction 'fninit' unimplemented
  1008. warn: Don't know what interrupt to clear for console.
  1009. 12516923000: system.pc.com_1.terminal: attach terminal 0
  1010. warn: i8042 "Write output port" command not implemented.
  1011. warn: i8042 "Write keyboard output buffer" command not implemented.
  1012. warn: Write to unknown i8042 (keyboard controller) command port.
  1013. hack: Assuming logical destinations are 1 << id.
  1014. panic: Resetting mouse wrap mode unimplemented.
  1015. Memory Usage: 1003456 KBytes
  1016. Program aborted at tick 632745027500
  1017. --- BEGIN LIBC BACKTRACE ---
  1018. ./build/X86/gem5.opt(_Z15print_backtracev+0x15)[0x12b8165]
  1019. ./build/X86/gem5.opt(_Z12abortHandleri+0x39)[0x12c32f9]
  1020. /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fe047a71390]
  1021. /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7fe046601428]
  1022. /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7fe04660302a]
  1023. ./build/X86/gem5.opt(_ZN6X86ISA8PS2Mouse11processDataEh+0xf5)[0x1391095]
  1024. ./build/X86/gem5.opt(_ZN6X86ISA5I80425writeEP6Packet+0x51c)[0x13927ec]
  1025. ./build/X86/gem5.opt(_ZN7PioPort10recvAtomicEP6Packet+0x66)[0x139f7b6]
  1026. ./build/X86/gem5.opt(_ZN15NoncoherentXBar10recvAtomicEP6Packets+0x200)[0x1434af0]
  1027. ./build/X86/gem5.opt(_ZN6Bridge15BridgeSlavePort10recvAtomicEP6Packet+0x5d)[0x140ee9d]
  1028. ./build/X86/gem5.opt(_ZN12CoherentXBar10recvAtomicEP6Packets+0x3e7)[0x1415b77]
  1029. ./build/X86/gem5.opt(_ZN15AtomicSimpleCPU8writeMemEPhjm5FlagsIjEPm+0x327)[0xa790a7]
  1030. ./build/X86/gem5.opt(_ZN17SimpleExecContext8writeMemEPhjm5FlagsIjEPm+0x19)[0xa856b9]
  1031. ./build/X86/gem5.opt(_ZNK10X86ISAInst2St7executeEP11ExecContextPN5Trace10InstRecordE+0x235)[0xfb9e65]
  1032. ./build/X86/gem5.opt(_ZN15AtomicSimpleCPU4tickEv+0x23c)[0xa784fc]
  1033. ./build/X86/gem5.opt(_ZN10EventQueue10serviceOneEv+0xc5)[0x12be0d5]
  1034. ./build/X86/gem5.opt(_Z9doSimLoopP10EventQueue+0x38)[0x12cd558]
  1035. ./build/X86/gem5.opt(_Z8simulatem+0x2eb)[0x12cdbdb]
  1036. ./build/X86/gem5.opt(_ZZN8pybind1112cpp_function10initializeIRPFP22GlobalSimLoopExitEventmES3_ImEINS_4nameENS_5scopeENS_7siblingENS_5arg_vEEEEvOT_PFT0_DpT1_EDpRKT2_ENUlRNS_6detail13function_callEE1_4_FUNESO_+0x41)[0x13fca11]
  1037. ./build/X86/gem5.opt(_ZN8pybind1112cpp_function10dispatcherEP7_objectS2_S2_+0x8d8)[0xfc7398]
  1038. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x7852)[0x7fe047d3b552]
  1039. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fe047e6501c]
  1040. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x6ffd)[0x7fe047d3acfd]
  1041. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x7124)[0x7fe047d3ae24]
  1042. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x7124)[0x7fe047d3ae24]
  1043. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fe047e6501c]
  1044. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCode+0x19)[0x7fe047d33b89]
  1045. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x613b)[0x7fe047d39e3b]
  1046. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fe047e6501c]
  1047. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x6ffd)[0x7fe047d3acfd]
  1048. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fe047e6501c]
  1049. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCode+0x19)[0x7fe047d33b89]
  1050. --- END LIBC BACKTRACE ---
  1051. Aborted (core dumped)
  1052. ....
  1053. Boot goes quite far, on telnet:
  1054. ....
  1055. ALSA device list:
  1056. No soundcards found.
  1057. ....
  1058. So just looks like we have to disable some Linux configs which GEM5 does not support... so fragile.
  1059. ===== GEM5 x86 copy upstream 2.6 configs on 4.9 kernel
  1060. The magic image provides its kernel configurations, so let's try that.
  1061. The configs are present at:
  1062. ....
  1063. wget http://www.gem5.org/dist/current/x86/config-x86.tar.bz2
  1064. ....
  1065. backed up at: https://github.com/cirosantilli/media/releases/tag/gem5
  1066. 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:
  1067. ....
  1068. panic: Invalid IDE control register offset: 0
  1069. Memory Usage: 931272 KBytes
  1070. Program aborted at tick 382834812000
  1071. --- BEGIN LIBC BACKTRACE ---
  1072. ./build/X86/gem5.opt(_Z15print_backtracev+0x15)[0x12b8165]
  1073. ./build/X86/gem5.opt(_Z12abortHandleri+0x39)[0x12c32f9]
  1074. /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fc2081c6390]
  1075. /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7fc206d56428]
  1076. /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7fc206d5802a]
  1077. ./build/X86/gem5.opt(_ZN7IdeDisk11readControlEmiPh+0xd9)[0xa96989]
  1078. ./build/X86/gem5.opt(_ZN13IdeController14dispatchAccessEP6Packetb+0x53e)[0xa947ae]
  1079. ./build/X86/gem5.opt(_ZN13IdeController4readEP6Packet+0xe)[0xa94a5e]
  1080. ./build/X86/gem5.opt(_ZN7PioPort10recvAtomicEP6Packet+0x3f)[0x139f78f]
  1081. ./build/X86/gem5.opt(_ZN15NoncoherentXBar10recvAtomicEP6Packets+0x200)[0x1434af0]
  1082. ./build/X86/gem5.opt(_ZN6Bridge15BridgeSlavePort10recvAtomicEP6Packet+0x5d)[0x140ee9d]
  1083. ./build/X86/gem5.opt(_ZN12CoherentXBar10recvAtomicEP6Packets+0x3e7)[0x1415b77]
  1084. ./build/X86/gem5.opt(_ZN15AtomicSimpleCPU7readMemEmPhj5FlagsIjE+0x3ef)[0xa780ef]
  1085. ./build/X86/gem5.opt(_ZN17SimpleExecContext7readMemEmPhj5FlagsIjE+0x11)[0xa85671]
  1086. ./build/X86/gem5.opt(_ZNK10X86ISAInst2Ld7executeEP11ExecContextPN5Trace10InstRecordE+0x130)[0xfb6c00]
  1087. ./build/X86/gem5.opt(_ZN15AtomicSimpleCPU4tickEv+0x23c)[0xa784fc]
  1088. ./build/X86/gem5.opt(_ZN10EventQueue10serviceOneEv+0xc5)[0x12be0d5]
  1089. ./build/X86/gem5.opt(_Z9doSimLoopP10EventQueue+0x38)[0x12cd558]
  1090. ./build/X86/gem5.opt(_Z8simulatem+0x2eb)[0x12cdbdb]
  1091. ./build/X86/gem5.opt(_ZZN8pybind1112cpp_function10initializeIRPFP22GlobalSimLoopExitEventmES3_ImEINS_4nameENS_5scopeENS_7siblingENS_5arg_vEEEEvOT_PFT0_DpT1_EDpRKT2_ENUlRNS_6detail13function_callEE1_4_FUNESO_+0x41)[0x13fca11]
  1092. ./build/X86/gem5.opt(_ZN8pybind1112cpp_function10dispatcherEP7_objectS2_S2_+0x8d8)[0xfc7398]
  1093. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x7852)[0x7fc208490552]
  1094. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fc2085ba01c]
  1095. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x6ffd)[0x7fc20848fcfd]
  1096. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x7124)[0x7fc20848fe24]
  1097. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x7124)[0x7fc20848fe24]
  1098. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fc2085ba01c]
  1099. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCode+0x19)[0x7fc208488b89]
  1100. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x613b)[0x7fc20848ee3b]
  1101. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fc2085ba01c]
  1102. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x6ffd)[0x7fc20848fcfd]
  1103. /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x85c)[0x7fc2085ba01c]
  1104. --- END LIBC BACKTRACE ---
  1105. Aborted (core dumped)
  1106. ....
  1107. ===== GEM5 x86 use upstream 2.6 configs and 2.6 kernel
  1108. 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
  1109. === initrd
  1110. The kernel can boot from an CPIO file, which is a directory serialization format much like tar: https://superuser.com/questions/343915/tar-vs-cpio-what-is-the-difference
  1111. The bootloader, which for us is QEMU itself, is then configured to put that CPIO into memory, and tell the kernel that it is there.
  1112. With this setup, you don't even need to give a root filesystem to the kernel, it just does everything in memory in a ramfs.
  1113. Try it out with:
  1114. ....
  1115. ./run -i
  1116. ....
  1117. Notice how it boots fine, even though `-drive` is not given.
  1118. Also as expected, there is no filesystem persistency, since we are doing everything in memory:
  1119. ....
  1120. date >f
  1121. poweroff
  1122. cat f
  1123. # can't open 'f': No such file or directory
  1124. ....
  1125. The main ingredients to get this working are:
  1126. * `BR2_TARGET_ROOTFS_CPIO=y`: make Buildroot generate `output/images/rootfs.cpio` in addition to the other images.
  1127. +
  1128. It is also possible to compress that image with other options.
  1129. * `qemu -initrd`: make QEMU put the image into memory and tell the kernel about it.
  1130. * `CONFIG_BLK_DEV_INITRD=y`: Compile the kernel with initrd support, see also: https://unix.stackexchange.com/questions/67462/linux-kernel-is-not-finding-the-initrd-correctly/424496#424496
  1131. +
  1132. Buildroot forces that option when `BR2_TARGET_ROOTFS_CPIO=y` is given
  1133. https://unix.stackexchange.com/questions/89923/how-does-linux-load-the-initrd-image asks how the mechanism works in more detail.
  1134. ==== initrd in desktop distros
  1135. Most modern desktop distributions have an initrd in their root disk to do early setup.
  1136. The rationale for this is described at: https://en.wikipedia.org/wiki/Initial_ramdisk
  1137. One obvious use case is having an encrypted root filesystem: you keep the initrd in an unencrypted partition, and then setup decryption from there.
  1138. I think GRUB then knows read common disk formats, and then loads that initrd to memory with a `/boot/grub/grub.cfg` directive of type:
  1139. initrd /initrd.img-4.4.0-108-generic
  1140. Related: https://stackoverflow.com/questions/6405083/initrd-and-booting-the-linux-kernel
  1141. ==== initramfs
  1142. initramfs is just like <<initrd>>, but you also glue the image directly to the kernel image itself.
  1143. So the only argument that QEMU needs is the `-kernel`, no `-drive` not even `-initrd`! Pretty cool.
  1144. Try it out with:
  1145. ....
  1146. ./run -a aarch64
  1147. ....
  1148. since our <<aarch64>> setup uses it by default.
  1149. In the background, it uses `BR2_TARGET_ROOTFS_INITRAMFS`, and this makes the kernel config option `CONFIG_INITRAMFS_SOURCE` point to the CPIO that will be embedded in the kernel image.
  1150. http://nairobi-embedded.org/initramfs_tutorial.html shows a full manual setup.
  1151. === ftrace
  1152. Trace a single function:
  1153. ....
  1154. cd /sys/kernel/debug/tracing/
  1155. # Stop tracing.
  1156. echo 0 > tracing_on
  1157. # Clear previous trace.
  1158. echo '' > trace
  1159. # List the available tracers, and pick one.
  1160. cat available_tracers
  1161. echo function > current_tracer
  1162. # List all functions that can be traced
  1163. # cat available_filter_functions
  1164. # Choose one.
  1165. echo __kmalloc >set_ftrace_filter
  1166. # Confirm that only __kmalloc is enabled.
  1167. cat enabled_functions
  1168. echo 1 > tracing_on
  1169. # Latest events.
  1170. head trace
  1171. # Observe trace continously, and drain seen events out.
  1172. cat trace_pipe &
  1173. ....
  1174. Sample output:
  1175. ....
  1176. # tracer: function
  1177. #
  1178. # entries-in-buffer/entries-written: 97/97 #P:1
  1179. #
  1180. # _-----=> irqs-off
  1181. # / _----=> need-resched
  1182. # | / _---=> hardirq/softirq
  1183. # || / _--=> preempt-depth
  1184. # ||| / delay
  1185. # TASK-PID CPU# |||| TIMESTAMP FUNCTION
  1186. # | | | |||| | |
  1187. head-228 [000] .... 825.534637: __kmalloc <-load_elf_phdrs
  1188. head-228 [000] .... 825.534692: __kmalloc <-load_elf_binary
  1189. head-228 [000] .... 825.534815: __kmalloc <-load_elf_phdrs
  1190. head-228 [000] .... 825.550917: __kmalloc <-__seq_open_private
  1191. head-228 [000] .... 825.550953: __kmalloc <-tracing_open
  1192. head-229 [000] .... 826.756585: __kmalloc <-load_elf_phdrs
  1193. head-229 [000] .... 826.756627: __kmalloc <-load_elf_binary
  1194. head-229 [000] .... 826.756719: __kmalloc <-load_elf_phdrs
  1195. head-229 [000] .... 826.773796: __kmalloc <-__seq_open_private
  1196. head-229 [000] .... 826.773835: __kmalloc <-tracing_open
  1197. head-230 [000] .... 827.174988: __kmalloc <-load_elf_phdrs
  1198. head-230 [000] .... 827.175046: __kmalloc <-load_elf_binary
  1199. head-230 [000] .... 827.175171: __kmalloc <-load_elf_phdrs
  1200. ....
  1201. Trace all possible functions, and draw a call graph:
  1202. ....
  1203. echo 1 > max_graph_depth
  1204. echo 1 > events/enable
  1205. echo function_graph > current_tracer
  1206. ....
  1207. Sample output:
  1208. ....
  1209. # CPU DURATION FUNCTION CALLS
  1210. # | | | | | | |
  1211. 0) 2.173 us | } /* ntp_tick_length */
  1212. 0) | timekeeping_update() {
  1213. 0) 4.176 us | ntp_get_next_leap();
  1214. 0) 5.016 us | update_vsyscall();
  1215. 0) | raw_notifier_call_chain() {
  1216. 0) 2.241 us | notifier_call_chain();
  1217. 0) + 19.879 us | }
  1218. 0) 3.144 us | update_fast_timekeeper();
  1219. 0) 2.738 us | update_fast_timekeeper();
  1220. 0) ! 117.147 us | }
  1221. 0) | _raw_spin_unlock_irqrestore() {
  1222. 0) 4.045 us | _raw_write_unlock_irqrestore();
  1223. 0) + 22.066 us | }
  1224. 0) ! 265.278 us | } /* update_wall_time */
  1225. ....
  1226. TODO: what do `+` and `!` mean?
  1227. Each `enable` under the `events/` tree enables a certain set of functions, the higher the `enable` more functions are enabled.
  1228. === QEMU user mode
  1229. This has nothing to do with the Linux kernel, but it is cool:
  1230. ....
  1231. sudo apt-get install qemu-user
  1232. ./build -a arm
  1233. cd buildroot/output.arm~/target
  1234. qemu-arm -L . bin/ls
  1235. ....
  1236. This uses QEMU's user-mode emulation mode that allows us to run cross-compiled userland programs directly on the host.
  1237. 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.
  1238. In other words, much cooler than:
  1239. ....
  1240. arm-linux-gnueabi-gcc -o hello -static hello.c
  1241. qemu-arm hello
  1242. ....
  1243. 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:
  1244. ....
  1245. package/qemu/qemu.mk:110: *** "Refusing to build qemu-user: target Linux version newer than host's.". Stop.
  1246. ....
  1247. since we are using a bleeding edge kernel, which is a sanity check in the Buildroot QEMU package.
  1248. 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?
  1249. GDB step debugging is also possible with:
  1250. ....
  1251. qemu-arm -g 1234 -L . bin/ls
  1252. ../host/usr/bin/arm-buildroot-linux-uclibcgnueabi-gdb -ex 'target remote localhost:1234'
  1253. ....
  1254. TODO: find source. Lazy now.
  1255. === Snapshot
  1256. https://stackoverflow.com/questions/40227651/does-qemu-emulator-have-checkpoint-function/48724371#48724371
  1257. QEMU allows us to take snapshots at any time through the monitor.
  1258. You can then restore CPU, memory and disk state back at any time.
  1259. qcow2 filesystems must be used for that to work.
  1260. To test it out, login into the VM with and run:
  1261. ....
  1262. /count.sh
  1263. ....
  1264. On another shell, take a snapshot:
  1265. ....
  1266. echo 'savevm my_snap_id' | ./qemumonitor
  1267. ....
  1268. The counting continues.
  1269. Restore the snapshot:
  1270. ....
  1271. echo 'loadvm my_snap_id' | ./qemumonitor
  1272. ....
  1273. and the counting goes back to where we saved. This shows that CPU and memory states were reverted.
  1274. We can also verify that the disk state is also reversed. Guest:
  1275. ....
  1276. echo 0 >f
  1277. ....
  1278. Monitor:
  1279. ....
  1280. echo 'savevm my_snap_id' | ./qemumonitor
  1281. ....
  1282. Guest:
  1283. ....
  1284. echo 1 >f
  1285. ....
  1286. Monitor:
  1287. ....
  1288. echo 'loadvm my_snap_id' | ./qemumonitor
  1289. ....
  1290. Guest:
  1291. ....
  1292. cat f
  1293. ....
  1294. And the output is `0`.
  1295. Our setup does not allow for snapshotting while using <<initrd>>.
  1296. == Failed action
  1297. === Record and replay
  1298. 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.
  1299. 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
  1300. 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?
  1301. == Insane action
  1302. === Run on host
  1303. 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.
  1304. It has however severe limitations, and you will soon see that the compilation time and disk usage are well worth it:
  1305. * 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].
  1306. * bugs can easily break you system. E.g.:
  1307. ** segfaults can trivially lead to a kernel crash, and require a reboot
  1308. ** 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`
  1309. ** 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]
  1310. * can't control which hardware is used, notably the CPU architecture
  1311. * can't step debug it with GDB easily
  1312. Still interested?
  1313. ....
  1314. cd kernel_module
  1315. ./make-host.sh
  1316. ....
  1317. 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:
  1318. ....
  1319. mv broken.c broken.c~
  1320. ./build_host
  1321. ....
  1322. Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:
  1323. ....
  1324. sudo insmod hello.ko
  1325. # Our module is there.
  1326. sudo lsmod | grep hello
  1327. # Last message should be: hello init
  1328. dmest -T
  1329. sudo rmmod hello
  1330. # Last message should be: hello exit
  1331. dmesg -T
  1332. # Not present anymore
  1333. sudo lsmod | grep hello
  1334. ....
  1335. === Hello host
  1336. Minimal host build system sanity check example.
  1337. ....
  1338. cd hello_host
  1339. make
  1340. insmod hello.ko
  1341. dmesg
  1342. rmmod hello.ko
  1343. dmesg
  1344. ....
  1345. == Conversation
  1346. === kmod
  1347. Multi-call executable that implements: `lsmod`, `insmod`, `rmmod`, and other tools on desktop distros such as Ubuntu 16.04, where e.g.:
  1348. ....
  1349. ls -l /bin/lsmod
  1350. ....
  1351. gives:
  1352. ....
  1353. lrwxrwxrwx 1 root root 4 Jul 25 15:35 /bin/lsmod -> kmod
  1354. ....
  1355. and:
  1356. ....
  1357. dpkg -l | grep -Ei
  1358. ....
  1359. contains:
  1360. ....
  1361. ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules
  1362. ....
  1363. BusyBox also implements its own version of those executables. There are some differences.
  1364. Buildroot also has a kmod package, but we are not using it since BusyBox' version is good enough so far.
  1365. This page will only describe features that differ from kmod to the BusyBox implementation.
  1366. Source code: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git
  1367. ==== module-init-tools
  1368. Name of a predecessor set of tools.
  1369. ==== modprobe
  1370. Load module under different name to avoid conflicts:
  1371. ....
  1372. sudo modprobe vmhgfs -o vm_hgfs
  1373. ....
  1374. === Device tree
  1375. `platform_device.c` together with its kernel and QEMU forks contains a minimal runnable example.
  1376. Good format descriptions:
  1377. * https://www.raspberrypi.org/documentation/configuration/device-tree.md
  1378. Minimal example
  1379. ....
  1380. /dts-v1/;
  1381. / {
  1382. a;
  1383. };
  1384. ....
  1385. Check correctness with:
  1386. ....
  1387. dtc a.dts
  1388. ....
  1389. Separate nodes are simply merged by node path, e.g.:
  1390. ....
  1391. /dts-v1/;
  1392. / {
  1393. a;
  1394. };
  1395. / {
  1396. b;
  1397. };
  1398. ....
  1399. then `dtc a.dts` gives:
  1400. ....
  1401. /dts-v1/;
  1402. / {
  1403. a;
  1404. b;
  1405. };
  1406. ....
  1407. === Directory structure
  1408. :leveloffset: +3
  1409. include::buildroot_patches/README.adoc[]
  1410. include::global_patch_dir/README.adoc[]
  1411. include::kernel_module/README.adoc[]
  1412. include::kernel_module/user/README.adoc[]
  1413. include::rootfs_overlay/README.adoc[]
  1414. :leveloffset: -3
  1415. === Maintainers
  1416. :leveloffset: +3
  1417. include::CONTRIBUTING.adoc[]
  1418. :leveloffset: -3
  1419. ==== How to update the Linux kernel?
  1420. ....
  1421. # Last point before out patches.
  1422. last_mainline_revision=v4.14
  1423. next_mainline_revision=v4.15
  1424. cd linux
  1425. # Create a branch before the rebase.
  1426. git branch "lkmc-${last_mainline_revision}"
  1427. git remote set-url origin git@github.com:cirosantilli/linux.git
  1428. git push
  1429. git remote add up git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
  1430. git fetch up
  1431. git rebase --onto "$next_mainline_revision" "$last_mainline_revision"
  1432. ./build -l
  1433. # Manually fix our kernel modules if necessary.
  1434. cd ..
  1435. git branch "buildroot-2017.08-linux-${last_mainline_revision}"
  1436. git add .
  1437. git commit -m "Linux ${next_mainline_revision}"
  1438. git push
  1439. ....
  1440. and update the README!
  1441. During update all you kernel modules may break since the kernel API is not stable.
  1442. They are usually trivial breaks of things moving around headers or to sub-structs.
  1443. The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.
  1444. This backwards compatibility is just awesome, it makes getting and running the latest master painless.
  1445. This also makes this repo the perfect setup to develop the Linux kernel.
  1446. ==== How to downgrade the Linux kernel?
  1447. 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.
  1448. The default Linux kernel version is bumped in Buildroot with commit messages of type:
  1449. ....
  1450. linux: bump default to version 4.9.6
  1451. ....
  1452. So you can try:
  1453. ....
  1454. git log --grep 'linux: bump default to version'
  1455. ....
  1456. Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in `/linux/Config.in`.
  1457. 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.
  1458. ==== How to add new Buildroot options?
  1459. ....
  1460. cd buildroot/output.x86_64~
  1461. make menuconfig
  1462. ....
  1463. Hit `/` and search for the settings.
  1464. Save and quit.
  1465. ....
  1466. diff .config.olg .config
  1467. ....
  1468. Copy and paste the diff additions to `buildroot_config_fragment`.
  1469. === About
  1470. This project is for people who want to learn and modify low level system components:
  1471. * Linux kernel and Linux kernel modules
  1472. * full systems emulators like QEMU and GEM5
  1473. * C standard libraries. This could also be put on a submodule if people show interest.
  1474. * Buildroot. We use and therefore a large feature set of it.
  1475. Phylosophy:
  1476. * automate as much as possible to make things more reproducible
  1477. * do everything from source to make things understandable and hackable
  1478. === Bibliography
  1479. Runnable stuff:
  1480. * 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.
  1481. * https://github.com/satoru-takeuchi/elkdat manual build process without Buildroot, very few and simple kernel modules
  1482. * https://github.com/tinyclub/linux-lab Buildroot based, no kernel modules?
  1483. * https://github.com/agelastic/eudyptula
  1484. * 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/
  1485. * 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.
  1486. Theory:
  1487. * http://nairobi-embedded.org you will fall here a lot when the hard Google queries start popping. They have covered everything we do here basically, but with a more manual approach, while this repo automates everything.
  1488. * https://balau82.wordpress.com awesome low level resource
  1489. * https://lwn.net
  1490. * http://www.makelinux.net