README.adoc 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  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 or gem5 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. "Tested" in x86, ARM and MIPS guests, Ubuntu 17.10 host.
  12. toc::[]
  13. == Getting started
  14. Reserve 12Gb of disk and run:
  15. ....
  16. git clone https://github.com/cirosantilli/linux-kernel-module-cheat
  17. cd linux-kernel-module-cheat
  18. ./configure && ./build && ./run
  19. ....
  20. The first build will take a while (link:https://stackoverflow.com/questions/10833672/buildroot-environment-with-host-toolchain[GCC], Linux kernel), e.g.:
  21. * 2 hours on a mid end 2012 laptop
  22. * 30 minutes on a high end 2017 desktop
  23. 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 at <<run-on-host>>, but as explained on that section, that is dangerous, limited, and will likely not work.
  24. After QEMU opens up, you can start playing with the kernel modules:
  25. ....
  26. root
  27. insmod /hello.ko
  28. insmod /hello2.ko
  29. rmmod hello
  30. rmmod hello2
  31. ....
  32. This should print to the screen:
  33. ....
  34. hello init
  35. hello2 init
  36. hello cleanup
  37. hello2 cleanup
  38. ....
  39. which are `printk` messages from `init` and `cleanup` methods of those modules.
  40. image:screenshot.png[image]
  41. All available modules can be found in the link:kernel_module/[`kernel_module` directory].
  42. === Module documentation
  43. ....
  44. head kernel_module/modulename.c
  45. ....
  46. Many of the modules have userland test scripts / executables with the same name as the module, e.g. form inside the guest:
  47. ....
  48. /modulename.sh
  49. /modulename.out
  50. ....
  51. The sources of those tests will further clarify what the corresponding kernel modules does. To find them on the host, do a quick:
  52. ....
  53. git ls-files | grep modulename
  54. ....
  55. === Rebuild
  56. After making changes to a package, you must explicitly tell it to be rebuilt.
  57. For example, you you modify the kernel modules, you must rebuild with:
  58. ....
  59. ./build -k
  60. ....
  61. which is just an alias for:
  62. ....
  63. ./build -- kernel_module-reconfigure
  64. ....
  65. where `kernel_module` is the name of out Buildroot package that contains the kernel modules.
  66. Other important targets are:
  67. ....
  68. ./build -- linux-reconfigure host-qemu-reconfigure
  69. ....
  70. which are aliased respectively to:
  71. ....
  72. ./build -l -q
  73. ....
  74. We don't rebuild by default because, even with `make` incremental rebuilds, the timestamp check takes a few annoying seconds.
  75. === Clean the build
  76. You did something crazy, and nothing seems to work anymore?
  77. All builds are stored under `buildroot/`,
  78. The most coarse thing you can do is:
  79. ....
  80. cd buildroot
  81. git checkout -- .
  82. git clean -xdf .
  83. ....
  84. To only nuke one architecture, do:
  85. ....
  86. rm -rf buildroot/output.x86_64~
  87. ....
  88. Only nuke one one package:
  89. ....
  90. rm -rf buildroot/output.x86_64~/build/host-qemu-custom
  91. ./build -q
  92. ....
  93. This is sometimes necessary when changing the version of the submodules, and then builds fail. We should try to understand why and report bugs.
  94. === Filesystem persistency
  95. The root filesystem is persistent across:
  96. ....
  97. ./run
  98. date >f
  99. sync
  100. poweroff
  101. ....
  102. then:
  103. ....
  104. ./run
  105. cat f
  106. ....
  107. This is particularly useful to re-run shell commands from the history of a previous session with `Ctrl + R`.
  108. However, when you do:
  109. ....
  110. ./build
  111. ....
  112. the disk image gets overwritten by a fresh filesystem and you lose all changes.
  113. 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.
  114. When booting from <<initrd>> however without a disk, persistency is lost.
  115. === Message control
  116. 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:
  117. ....
  118. dmesg -n 1
  119. ....
  120. See also: https://superuser.com/questions/351387/how-to-stop-kernel-messages-from-flooding-my-console
  121. You can scroll up a bit on the default TTY with:
  122. ....
  123. Shift + PgUp
  124. ....
  125. but I never managed to increase that buffer:
  126. * https://askubuntu.com/questions/709697/how-to-increase-scrollback-lines-in-ubuntu14-04-2-server-edition
  127. * https://unix.stackexchange.com/questions/346018/how-to-increase-the-scrollback-buffer-size-for-tty
  128. The superior alternative is to use text mode or a telnet connection.
  129. === Text mode
  130. Show serial console directly on the current terminal, without opening a QEMU window:
  131. ....
  132. ./run -n
  133. ....
  134. To quit QEMU forcefully, just use Ctrl + C as usual.
  135. This mode is very useful to:
  136. * 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
  137. * copy and paste commands and stdout output to / from host
  138. * have a large scroll buffer, and be able to search it, e.g. by using GNU `screen` on host
  139. Limitations:
  140. * TODO: Ctrl + C kills the emulator, and not sent to guest processes. See:
  141. +
  142. --
  143. ** https://unix.stackexchange.com/questions/167165/how-to-pass-ctrl-c-in-qemu
  144. ** https://github.com/cloudius-systems/osv/issues/49
  145. --
  146. +
  147. It is also hard to enter the monitor for the same reason:
  148. --
  149. * http://stackoverflow.com/questions/14165158/how-to-switch-to-qemu-monitor-console-when-running-with-curses
  150. * https://superuser.com/questions/488263/how-to-switch-to-the-qemu-control-panel-with-nographics
  151. --
  152. +
  153. Our workaround is:
  154. +
  155. ....
  156. ./qemumonitor
  157. ....
  158. +
  159. I think the problem was reversed in older QEMU versions: https://superuser.com/questions/1087859/how-to-quit-the-qemu-monitor-when-not-using-a-gui/1211516#1211516
  160. +
  161. This is however fortunate when running QEMU with GDB, as the Ctrl + C reaches GDB and breaks.
  162. * 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.
  163. === Automatic startup commands
  164. When debugging a module, it becomes tedious to wait for build and re-type:
  165. ....
  166. root
  167. /modulename.sh
  168. ....
  169. every time.
  170. Instead, you can either run them from a minimal init:
  171. ....
  172. ./run -e 'init=/eval.sh - lkmc_eval="insmod /hello.ko;/poweroff.out"' -n
  173. ....
  174. or if the script is large, add it to a gitignored file that will go into the guest:
  175. ....
  176. echo '
  177. insmod /hello.ko
  178. /poweroff.out
  179. ' > rootfs_overlay/ignore.sh
  180. ./run -e 'init=/ignore.sh' -n
  181. ....
  182. or run them at the end of the BusyBox init, which does things like setting up networking:
  183. ....
  184. ./run -e '- lkmc_eval="insmod /hello.ko;wget -S google.com;poweroff.out;"'
  185. ....
  186. or add them to a new `init.d` entry to run at the end o the BusyBox init:
  187. ....
  188. cp rootfs_overlay/etc/init.d/S98 rootfs_overlay/etc/init.d/S99
  189. vim S99
  190. ./build
  191. ./run
  192. ....
  193. and they will be run automatically before the login prompt.
  194. `S99` is a git tracked convenience symlink to the gitignored `rootfs_overlay/etc/init.d/S99`
  195. 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`.
  196. === Kernel version
  197. We try to use the latest possible kernel major release version.
  198. In QEMU:
  199. ....
  200. cat /proc/version
  201. ....
  202. or in the source:
  203. ....
  204. cd linux
  205. git log | grep -E ' Linux [0-9]+\.' | head
  206. ....
  207. Build configuration can be observed in guest with:
  208. ....
  209. zcat /proc/config.gz
  210. ....
  211. or on host:
  212. ....
  213. cat buildroot/output.*~/build/linux-custom/.config
  214. ....
  215. === Kernel command line parameters
  216. 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.
  217. This allows us to control the behaviour of the kernel without rebuilding anything.
  218. With QEMU, QEMU itself acts as the bootloader, and provides the `-append` option and we expose it through `./run -e`, e.g.:
  219. ....
  220. ./run -e 'foo bar'
  221. ....
  222. Then inside the host, you can check which options were given with:
  223. ....
  224. cat /proc/cmdline
  225. ....
  226. They are also printed at the beginning of the boot message:
  227. ....
  228. dmesg | grep "Command line"
  229. ....
  230. See also:
  231. * https://unix.stackexchange.com/questions/48601/how-to-display-the-linux-kernel-command-line-parameters-given-for-the-current-bo
  232. * https://askubuntu.com/questions/32654/how-do-i-find-the-boot-parameters-used-by-the-running-kernel
  233. The arguments are documented in the kernel documentation: https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  234. When dealing with real boards, extra command line options are provided on some magic bootloader configuration file, e.g.:
  235. * GRUB configuration files: https://askubuntu.com/questions/19486/how-do-i-add-a-kernel-boot-parameter
  236. * 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
  237. === QEMU GUI is unresponsive
  238. 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.
  239. We have not managed to track this problem down yet, but the following workaround always works:
  240. ....
  241. Ctrl + Shift + U
  242. Ctrl + C
  243. root
  244. ....
  245. This started happening when we switched to building QEMU through Buildroot, and has not been observed on later Ubuntu.
  246. Using text mode is another workaround if you don't need GUI features.
  247. === Debug QEMU
  248. When you start interacting with QEMU hardware, it is useful to see what is going on inside of QEMU itself.
  249. This is of course trivial since QEMU is just an userland program on the host, but we make it a bit easier with:
  250. ....
  251. ./run -D
  252. ....
  253. Then you could:
  254. ....
  255. b edu_mmio_read
  256. c
  257. ....
  258. And in QEMU:
  259. ....
  260. /pci.sh
  261. ....
  262. 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.
  263. 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.
  264. [[gdb]]
  265. == GDB step debugging
  266. To GDB step debug the Linux kernel, first run:
  267. ....
  268. ./run -d
  269. ....
  270. If you want to break immediately at a symbol, e.g. `start_kernel` of the boot sequence, run on another shell:
  271. ....
  272. ./rungdb start_kernel
  273. ....
  274. Now QEMU will stop there, and you can use the normal GDB commands:
  275. ....
  276. l
  277. n
  278. c
  279. ....
  280. To skip the boot, run just:
  281. ....
  282. ./rungdb
  283. ....
  284. and when you want to break, do `Ctrl + C` from GDB.
  285. To have some fun, you can first run inside QEMU:
  286. ....
  287. /count.sh
  288. ....
  289. which counts to infinity to stdout, and then in GDB:
  290. ....
  291. Ctrl + C
  292. break sys_write
  293. continue
  294. continue
  295. continue
  296. ....
  297. And you now control the counting from GDB.
  298. See also:
  299. * http://stackoverflow.com/questions/11408041/how-to-debug-the-linux-kernel-with-gdb-and-qemu/33203642#33203642
  300. * http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/42316607#42316607
  301. `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.
  302. === Kernel module debugging
  303. Loadable kernel modules are a bit trickier since the kernel can place them at different memory locations depending on load order.
  304. So we cannot set the breakpoints before `insmod`.
  305. However, the Linux kernel GDB scripts offer the `lx-symbols` command, which takes care of that beautifully for us:
  306. ....
  307. ./run -d
  308. ./rungdb
  309. ....
  310. In QEMU:
  311. ....
  312. insmod /timer.ko
  313. ....
  314. In GDB, hit `Ctrl + C`, and note how it says:
  315. ....
  316. scanning for modules in /home/ciro/bak/git/linux-kernel-module-cheat/buildroot/output.x86_64~/build/linux-custom
  317. loading @0xffffffffc0000000: ../kernel_module-1.0//timer.ko
  318. ....
  319. That's `lx-symbols` working! Now simply:
  320. ....
  321. b lkmc_timer_callback
  322. c
  323. c
  324. c
  325. ....
  326. and we now control the callback from GDB!
  327. Just don't forget to remove your breakpoints after `rmmod`, or they will point to stale memory locations.
  328. TODO: why does `break work_func` for `insmod kthread.ko` not break the first time I `insmod`, but breaks the second time?
  329. See also: http://stackoverflow.com/questions/28607538/how-to-debug-linux-kernel-modules-with-qemu/44095831#44095831
  330. ==== Bypass lx-symbols
  331. Useless, but a good way to show how hardcore you are. From inside QEMU:
  332. ....
  333. insmod /fops.ko
  334. cat /proc/modules
  335. ....
  336. This will give a line of form:
  337. ....
  338. fops 2327 0 - Live 0xfffffffa00000000
  339. ....
  340. And then tell GDB where the module was loaded with:
  341. ....
  342. Ctrl + C
  343. add-symbol-file ../kernel_module-1.0/fops.ko 0xfffffffa00000000
  344. ....
  345. === Debug kernel early boot
  346. TODO: why can't we break at early startup stuff such as:
  347. ....
  348. ./rungdb extract_kernel
  349. ./rungdb main
  350. ....
  351. See also: https://stackoverflow.com/questions/2589845/what-are-the-first-operations-that-the-linux-kernel-executes-on-boot
  352. === GDB call
  353. GDB can call functions as explained at: https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb
  354. However this is failing for us:
  355. * some symbols are not visible to `call` even though `b` sees them
  356. * for those that are, `call` fails with an E14 error
  357. E.g.: if we break on `sys_write` on `/count.sh`:
  358. ....
  359. >>> call printk(0, "asdf")
  360. Could not fetch register "orig_rax"; remote failure reply 'E14'
  361. >>> b printk
  362. Breakpoint 2 at 0xffffffff81091bca: file kernel/printk/printk.c, line 1824.
  363. >>> call fdget_pos(fd)
  364. No symbol "fdget_pos" in current context.
  365. >>> b fdget_pos
  366. Breakpoint 3 at 0xffffffff811615e3: fdget_pos. (9 locations)
  367. >>>
  368. ....
  369. even though `fdget_pos` is the first thing `sys_write` does:
  370. ....
  371. 581 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
  372. 582 size_t, count)
  373. 583 {
  374. 584 struct fd f = fdget_pos(fd);
  375. ....
  376. See also: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/19
  377. == KGDB
  378. KGDB is kernel dark magic that allows you to GDB the kernel on real hardware without any extra hardware support.
  379. It is useless with QEMU since we already have full system visibility with `-gdb`, but this is a good way to learn it.
  380. 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.
  381. Usage:
  382. ....
  383. ./run -k
  384. ./rungdb -k
  385. ....
  386. In GDB:
  387. ....
  388. c
  389. ....
  390. In QEMU:
  391. ....
  392. /count.sh &
  393. /kgdb.sh
  394. ....
  395. In GDB:
  396. ....
  397. b sys_write
  398. c
  399. c
  400. c
  401. c
  402. ....
  403. And now you can count from GDB!
  404. 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.
  405. See also:
  406. * https://github.com/torvalds/linux/blob/v4.9/Documentation/DocBook/kgdb.tmpl
  407. * https://stackoverflow.com/questions/22004616/qemu-kernel-debugging-with-kgdb/44197715#44197715
  408. === KGDB kernel modules
  409. In QEMU:
  410. ....
  411. /kgdb-mod.sh
  412. ....
  413. In GDB:
  414. ....
  415. lx-symbols ../kernel_module-1.0/
  416. b fop_write
  417. c
  418. c
  419. c
  420. ....
  421. and you now control the count.
  422. TODO: if I `-ex lx-symbols` to the `gdb` command, just like done for QEMU `-gdb`, the kernel oops. How to automate this step?
  423. === KDB
  424. If you modify `runqemu` to use:
  425. ....
  426. -append kgdboc=kbd
  427. ....
  428. instead of `kgdboc=ttyS0,115200`, you enter a different debugging mode called KDB.
  429. Usage: in QEMU:
  430. ....
  431. [0]kdb> go
  432. ....
  433. Boot finishes, then:
  434. ....
  435. /kgdb.sh
  436. ....
  437. And you are back in KDB. Now you can:
  438. ....
  439. [0]kdb> help
  440. [0]kdb> bp sys_write
  441. [0]kdb> go
  442. ....
  443. And you will break whenever `sys_write` is hit.
  444. The other KDB commands allow you to instruction steps, view memory, registers and some higher level kernel runtime data.
  445. 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).
  446. == gdbserver
  447. Step debug userland processes to understand how they are talking to the kernel.
  448. In guest:
  449. ....
  450. /gdbserver.sh /myinsmod.out /hello.ko
  451. ....
  452. In host:
  453. ....
  454. ./rungdbserver kernel_module-1.0/user/myinsmod.out
  455. ....
  456. You can find the executable with:
  457. ....
  458. find buildroot/output.x86_64~/build -name myinsmod.out
  459. ....
  460. TODO: automate the path finding:
  461. * 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.
  462. * `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.
  463. +
  464. E.g. `pciutils` has for `lspci`:
  465. +
  466. ....
  467. define PCIUTILS_INSTALL_STAGING_CMDS
  468. $(TARGET_MAKE_ENV) $(MAKE1) -C $(@D) $(PCIUTILS_MAKE_OPTS) \
  469. PREFIX=$(STAGING_DIR)/usr SBINDIR=$(STAGING_DIR)/usr/bin \
  470. install install-lib install-pcilib
  471. endef
  472. ....
  473. +
  474. and the docs describe the `*_INSTALL_STAGING` per package config, which is normally set for shared library packages.
  475. +
  476. Feature request: https://bugs.busybox.net/show_bug.cgi?id=10386
  477. An implementation overview can be found at: https://reverseengineering.stackexchange.com/questions/8829/cross-debugging-for-mips-elf-with-qemu-toolchain/16214#16214
  478. === gdbserver different archs
  479. As usual, different archs work with:
  480. ....
  481. ./rungdbserver -a arm kernel_module-1.0/user/myinsmod.out
  482. ....
  483. === gdbserver BusyBox
  484. BusyBox executables are all symlinks, so if you do on guest:
  485. ....
  486. /gdbserver.sh ls
  487. ....
  488. on host you need:
  489. ....
  490. ./rungdbserver busybox-1.26.2/busybox
  491. ....
  492. === gdbserver shared libraries
  493. Our setup gives you the rare opportunity to step debug libc and other system libraries e.g. with:
  494. ....
  495. b open
  496. c
  497. ....
  498. Or simply by stepping into calls:
  499. ....
  500. s
  501. ....
  502. This is made possible by the GDB command:
  503. ....
  504. set sysroot ${buildroot_out_dir}/staging
  505. ....
  506. which automatically finds unstripped shared libraries on the host for us.
  507. See also: https://stackoverflow.com/questions/8611194/debugging-shared-libraries-with-gdbserver/45252113#45252113
  508. === Debug userland process without gdbserver
  509. QEMU `-gdb` GDB breakpoints are set on virtual addresses, so you can in theory debug userland processes as well.
  510. * https://stackoverflow.com/questions/26271901/is-it-possible-to-use-gdb-and-qemu-to-debug-linux-user-space-programs-and-kernel
  511. * https://stackoverflow.com/questions/16273614/debug-init-on-qemu-using-gdb
  512. 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:
  513. * the kernel might switch context to another process, and you would enter "garbage"
  514. * TODO step into shared libraries. If I attempt to load them explicitly:
  515. +
  516. ....
  517. (gdb) sharedlibrary ../../staging/lib/libc.so.0
  518. No loaded shared libraries match the pattern `../../staging/lib/libc.so.0'.
  519. ....
  520. +
  521. since GDB does not know that libc is loaded.
  522. Custom init process:
  523. * Shell 1:
  524. +
  525. ....
  526. ./run -d -e 'init=/sleep_forever.out' -n
  527. ....
  528. * Shell 2:
  529. +
  530. ....
  531. ./rungdb-user kernel_module-1.0/user/sleep_forever.out main
  532. ....
  533. BusyBox custom init process:
  534. * Shell 1:
  535. +
  536. ....
  537. ./run -d -e 'init=/bin/ls' -n
  538. ....
  539. * Shell 2:
  540. +
  541. ....
  542. ./rungdb-user -h busybox-1.26.2/busybox ls_main
  543. ....
  544. This follows BusyBox' convention of calling the main for each executable as `<exec>_main` since the `busybox` executable has many "mains".
  545. BusyBox default init process:
  546. * Shell 1:
  547. +
  548. ....
  549. ./run -d -n
  550. ....
  551. * Shell 2:
  552. +
  553. ....
  554. ./rungdb-user -h busybox-1.26.2/busybox init_main
  555. ....
  556. This cannot be debugged in another way without modifying the source, or `/sbin/init` exits early with:
  557. ....
  558. "must be run as PID 1"
  559. ....
  560. Non-init process:
  561. * Shell 1
  562. +
  563. ....
  564. ./run -d -n
  565. ....
  566. * Shell 2
  567. +
  568. ....
  569. ./rungdb-user kernel_module-1.0/user/sleep_forever.out
  570. Ctrl + C
  571. b main
  572. continue
  573. ....
  574. * Shell 1
  575. +
  576. ....
  577. /sleep_forever.out
  578. ....
  579. This is of least reliable setup as there might be other processes that use the given virtual address.
  580. == Architecture
  581. The portability of the kernel and toolchains is amazing: change an option and most things magically work on completely different hardware.
  582. To use `arm` instead of x86 for example:
  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. Known quirks of the supported architectures are documented in this section.
  594. === arm
  595. TODOs:
  596. * only managed to run in the terminal interface (but weirdly a blank QEMU window is still opened)
  597. * GDB not connecting to KGDB. Possibly linked to `-serial stdio`. See also: https://stackoverflow.com/questions/14155577/how-to-use-kgdb-on-arm
  598. * `/poweroff.out` does not exit QEMU nor gem5, the terminal just hangs: https://stackoverflow.com/questions/31990487/how-to-cleanly-exit-qemu-after-executing-bare-metal-program-without-user-interve
  599. +
  600. A blunt resolution for QEMU is on host:
  601. +
  602. ....
  603. pkill qemu
  604. ....
  605. +
  606. On gem5, it is possible to use the `m5` instrumentation from guest as a good workaround:
  607. +
  608. ....
  609. m5 exit
  610. ....
  611. * GDB step debugging of kernel modules broke at some point. This happens at 6420c31986e064c81561da8f2be0bd33483af598 on kernel v4.15, 6b0f89a8b43e8d33d3a3a436ed827f962da3008a v4.14 and 5ad68edd000685c016c45e344470f2c1867b8e39 v4.12 and also if kernel 4.9.6 is checked out. So maybe it was never working in the first place, but we never noticed?
  612. +
  613. Just afte GDB connects, we get the following message from the kernel GDB Python scripts:
  614. ....
  615. loading vmlinux
  616. Traceback (most recent call last):
  617. File "/home/ciro/bak/git/linux-kernel-module-cheat/buildroot/output.arm~/build/linux-custom/scripts/gdb/linux/symbols.py", line 163, in invoke
  618. self.load_all_symbols()
  619. File "/home/ciro/bak/git/linux-kernel-module-cheat/buildroot/output.arm~/build/linux-custom/scripts/gdb/linux/symbols.py", line 150, in load_all_symbols
  620. [self.load_module_symbols(module) for module in module_list]
  621. File "/home/ciro/bak/git/linux-kernel-module-cheat/buildroot/output.arm~/build/linux-custom/scripts/gdb/linux/symbols.py", line 110, in load_module_symbols
  622. module_name = module['name'].string()
  623. File "/home/ciro/bak/git/linux-kernel-module-cheat/buildroot/output.arm~/host/lib/python2.7/encodings/utf_8.py", line 16, in decode
  624. return codecs.utf_8_decode(input, errors, True)
  625. UnicodeDecodeError: 'utf8' codec can't decode byte 0x9f in position 2: invalid start byte
  626. Error occurred in Python command: 'utf8' codec can't decode byte 0x9f in position 2: invalid start byte
  627. ....
  628. +
  629. and then after inserting the module, symbols are not found, presumably because `lx-symbols` never ran.
  630. === aarch64
  631. As usual, we use Buildroot's recommended QEMU setup QEMU `aarch64` setup:
  632. * https://github.com/buildroot/buildroot/blob/2017.08/board/qemu/aarch64-virt/readme.txt
  633. * https://github.com/buildroot/buildroot/blob/2017.08/configs/qemu_aarch64_virt_defconfig
  634. This makes aarch64 a bit different from `arm`:
  635. * uses `-M virt`. https://wiki.qemu.org/Documentation/Platforms/ARM explains:
  636. +
  637. ____
  638. 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.
  639. ____
  640. +
  641. `-M virt` has some limitations, e.g. I could not pass `-drive if=scsi` as for `arm`, and so <<Snapshot>> fails.
  642. +
  643. * uses <<initramfs>>, so thre is no filesystem persistency.
  644. So, as long as you keep those points in mind, our `-a aarch64` offers an interesting different setup to play with.
  645. TODOs:
  646. * <<gdb>> appears to be stuck on an infinite loop:
  647. +
  648. ....
  649. no module object found for ''
  650. ....
  651. === mips64
  652. Keep in mind that MIPS has the worst support compared to our other architectures due to the smaller community. Patches welcome as usual.
  653. TODOs:
  654. * networking is not working. See also:
  655. ** https://stackoverflow.com/questions/21496449/networking-is-not-working-on-qemu-guest-malta-mips
  656. ** https://unix.stackexchange.com/questions/208266/setting-up-qemu-and-mipsel-networking-trouble
  657. ** https://unix.stackexchange.com/questions/354127/qemu-mips-and-debian
  658. * <<gdb>> does not work properly, does not find `start_kernel`
  659. == init
  660. When the Linux kernel finishes booting, it runs an executable as the first and only userland process.
  661. The default path is `/init`, but we an set a custom one with the `init=` <<kernel-command-line-parameters,kernel command line parameter>>.
  662. This process is then responsible for setting up the entire userland (or destroying everything when you want to have fun).
  663. This typically means reading some configuration files (e.g. `/etc/initrc`) and forking a bunch of userland executables based on those files.
  664. systemd is a "popular" `/init` implementation for desktop distros as of 2017.
  665. BusyBox provides its own minimalistic init implementation which Buildroot uses by default.
  666. === Custom init
  667. Is the default BusyBox `/init` too bloated for you, minimalism freak?
  668. No problem, just use the `init` kernel boot parameter:
  669. ....
  670. ./run -e 'init=/sleep_forever.out'
  671. ....
  672. Remember that shell scripts can also be used for `init` https://unix.stackexchange.com/questions/174062/init-as-a-shell-script/395375#395375:
  673. ....
  674. ./run -e 'init=/count.sh'
  675. ....
  676. Also remember that if your init returns, the kernel will panic, there are just two non-panic possibilities:
  677. * run forever in a loop or long sleep
  678. * `poweroff` the machine
  679. === Disable networking
  680. 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.
  681. To disable networking, use:
  682. ....
  683. ./build -p -n
  684. ....
  685. To restore it, run:
  686. ....
  687. ./build -- initscripts-reconfigure
  688. ....
  689. === The init environment
  690. The docs make it clear https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
  691. ____
  692. 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.
  693. ____
  694. And you can try it out with:
  695. ....
  696. ./run -e 'init=/init_env_poweroff.sh - asdf=qwer zxcv' -n
  697. ....
  698. == modprobe
  699. If you are feeling fancy, you can also insert modules with:
  700. ....
  701. modprobe dep2
  702. lsmod
  703. # dep and dep2
  704. ....
  705. This method also deals with module dependencies, which we almost don't use to make examples simpler:
  706. * https://askubuntu.com/questions/20070/whats-the-difference-between-insmod-and-modprobe
  707. * https://stackoverflow.com/questions/22891705/whats-the-difference-between-insmod-and-modprobe
  708. Removal also removes required modules that have zero usage count:
  709. ....
  710. modprobe -r dep2
  711. lsmod
  712. # Nothing.
  713. ....
  714. but it can't know if you actually insmodded them separately or not:
  715. ....
  716. modprobe dep
  717. modprobe dep2
  718. modprobe -r dep2
  719. # Nothing.
  720. ....
  721. so it is a bit risky.
  722. `modprobe` searches for modules under:
  723. ....
  724. ls /lib/modules/*/extra/
  725. ....
  726. Kernel modules built from the Linux mainline tree with `CONFIG_SOME_MOD=m`, are automatically available with `modprobe`, e.g.:
  727. ....
  728. modprobe dummy-irq
  729. ....
  730. == X11
  731. Only tested successfully in `x86_64`.
  732. Build:
  733. ....
  734. ./build -i buildroot_config_fragment_x11
  735. ./run
  736. ....
  737. 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.
  738. Inside QEMU:
  739. ....
  740. startx
  741. ....
  742. image:x11.png[image]
  743. More details: https://unix.stackexchange.com/questions/70931/how-to-install-x11-on-my-own-linux-buildroot-system/306116#306116
  744. 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.
  745. === X11 ARM
  746. On ARM, `startx` hangs at a message:
  747. ....
  748. vgaarb: this pci device is not a vga device
  749. ....
  750. and nothing shows on the screen, and:
  751. ....
  752. grep EE /var/log/Xorg.0.log
  753. ....
  754. says:
  755. ....
  756. (EE) Failed to load module "modesetting" (module does not exist, 0)
  757. ....
  758. A friend told me this but I haven't tried it yet:
  759. * `xf86-video-modesetting` is likely the missing ingredient, but it does not seem possible to activate it from Buildroot currently without patching things.
  760. * `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`
  761. == Count boot instructions
  762. * https://www.quora.com/How-many-instructions-does-a-typical-Linux-kernel-boot-take
  763. * https://github.com/cirosantilli/chat/issues/31
  764. * https://rwmj.wordpress.com/2016/03/17/tracing-qemu-guest-execution/
  765. * `qemu/docs/tracing.txt` and `qemu/docs/replay.txt`
  766. * https://stackoverflow.com/questions/39149446/how-to-use-qemus-simple-trace-backend/46497873#46497873
  767. Results:
  768. [options="header"]
  769. |===
  770. |Commit |Arch |Simulator |Instruction count
  771. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b |arm |QEMU |680k
  772. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b |arm |gem5 AtomicSimpleCPU |160M
  773. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b |arm |gem5 HPI |155M
  774. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b |x86_64 |QEMU |3M
  775. |7228f75ac74c896417fb8c5ba3d375a14ed4d36b |x86_64 |gem5 AtomicSimpleCPU |528M
  776. |===
  777. QEMU:
  778. ....
  779. time ./run -n -e 'init=/poweroff.out' -- -trace exec_tb,file=trace
  780. time ./qemu/scripts/simpletrace.py buildroot/output.x86_64~/build/host-qemu-custom/trace-events-all trace >trace.txt
  781. wc -l trace.txt
  782. sed '/0x1000000/q' trace.txt >trace-boot.txt
  783. wc -l trace-boot.txt
  784. ....
  785. gem5:
  786. ....
  787. ./run -a arm -g -e 'init=/eval.sh - lkmc_eval="m5 exit"' -n
  788. # Or:
  789. # ./run -a arm -g -e 'init=/eval.sh - lkmc_eval="m5 exit"' -n -- --cpu-type=HPI --caches
  790. grep sim_insts m5out/stats.txt
  791. ....
  792. Notes:
  793. * `-n` is a good idea to reduce the chances that you send unwanted non-deterministic mouse or keyboard clicks to the VM.
  794. * `-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.
  795. +
  796. 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.
  797. +
  798. 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`.
  799. * `0x1000000` is the address where QEMU puts the Linux kernel at with `-kernel` in x86.
  800. +
  801. It can be found from:
  802. +
  803. ....
  804. readelf -e buildroot/output.x86_64~/build/linux-*/vmlinux | grep Entry
  805. ....
  806. +
  807. TODO confirm further. If I try to break there with:
  808. +
  809. ....
  810. ./rungdb *0x1000000
  811. ....
  812. +
  813. 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:
  814. +
  815. ....
  816. ./rungdb extract_kernel
  817. ....
  818. +
  819. It only appears once on every log I've seen so far, checked with `grep 0x1000000 trace.txt`
  820. +
  821. 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.
  822. * 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:
  823. +
  824. ....
  825. ./rungdb-user kernel_module-1.0/user/poweroff.out main
  826. ....
  827. +
  828. And get that from the traces, e.g. if the address is `4003a0`, then we search:
  829. +
  830. ....
  831. grep -n 4003a0 trace.txt
  832. ....
  833. +
  834. 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.
  835. * gem5 simulates memory latencies. So I think that the CPU loops idle while waiting for memory, and counts will be higher.
  836. This works because we have already done the following with QEMU:
  837. * `./configure --enable-trace-backends=simple`. This logs in a binary format to the trace file.
  838. +
  839. It makes 3x execution faster than the default trace backend which logs human readable data to stdout.
  840. +
  841. 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.
  842. * 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/
  843. Possible improvements:
  844. * to disable networking. Is replacing `init` enough?
  845. ** https://superuser.com/questions/181254/how-do-you-boot-linux-with-networking-disabled
  846. ** https://superuser.com/questions/684005/how-does-one-permanently-disable-gnu-linux-networking/1255015#1255015
  847. +
  848. `CONFIG_NET=n` did not significantly reduce instruction, so maybe replacing `init` is enough.
  849. * logging with the default backend `log` greatly slows down the CPU, and in particular leads to this during kernel boot:
  850. +
  851. ....
  852. All QSes seen, last rcu_sched kthread activity 5252 (4294901421-4294896169), jiffies_till_next_fqs=1, root ->qsmask 0x0
  853. swapper/0 R running task 0 1 0 0x00000008
  854. ffff880007c03ef8 ffffffff8107aa5d ffff880007c16b40 ffffffff81a3b100
  855. ffff880007c03f60 ffffffff810a41d1 0000000000000000 0000000007c03f20
  856. fffffffffffffedc 0000000000000004 fffffffffffffedc ffffffff00000000
  857. Call Trace:
  858. <IRQ> [<ffffffff8107aa5d>] sched_show_task+0xcd/0x130
  859. [<ffffffff810a41d1>] rcu_check_callbacks+0x871/0x880
  860. [<ffffffff810a799f>] update_process_times+0x2f/0x60
  861. ....
  862. +
  863. in which the boot appears to hang for a considerable time.
  864. * Confirm that the kernel enters at `0x1000000`, or where it enters. Once we have this, we can exclude what comes before in the BIOS.
  865. == initrd
  866. 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
  867. 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.
  868. 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.
  869. Try it out with:
  870. ....
  871. ./run -i
  872. ....
  873. Notice how it boots fine, even though `-drive` is not given.
  874. Also as expected, there is no filesystem persistency, since we are doing everything in memory:
  875. ....
  876. date >f
  877. poweroff
  878. cat f
  879. # can't open 'f': No such file or directory
  880. ....
  881. This can be good for automated tests, as it ensures that you are using a pristine unmodified system image every time.
  882. The main ingredients to get this working are:
  883. * `BR2_TARGET_ROOTFS_CPIO=y`: make Buildroot generate `output/images/rootfs.cpio` in addition to the other images.
  884. +
  885. It is also possible to compress that image with other options.
  886. * `qemu -initrd`: make QEMU put the image into memory and tell the kernel about it.
  887. * `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
  888. +
  889. Buildroot forces that option when `BR2_TARGET_ROOTFS_CPIO=y` is given
  890. https://unix.stackexchange.com/questions/89923/how-does-linux-load-the-initrd-image asks how the mechanism works in more detail.
  891. === initrd in desktop distros
  892. Most modern desktop distributions have an initrd in their root disk to do early setup.
  893. The rationale for this is described at: https://en.wikipedia.org/wiki/Initial_ramdisk
  894. One obvious use case is having an encrypted root filesystem: you keep the initrd in an unencrypted partition, and then setup decryption from there.
  895. 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:
  896. initrd /initrd.img-4.4.0-108-generic
  897. Related: https://stackoverflow.com/questions/6405083/initrd-and-booting-the-linux-kernel
  898. === initramfs
  899. initramfs is just like <<initrd>>, but you also glue the image directly to the kernel image itself.
  900. So the only argument that QEMU needs is the `-kernel`, no `-drive` not even `-initrd`! Pretty cool.
  901. Try it out with:
  902. ....
  903. ./run -a aarch64
  904. ....
  905. since our <<aarch64>> setup uses it by default.
  906. 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.
  907. http://nairobi-embedded.org/initramfs_tutorial.html shows a full manual setup.
  908. == ftrace
  909. Trace a single function:
  910. ....
  911. cd /sys/kernel/debug/tracing/
  912. # Stop tracing.
  913. echo 0 > tracing_on
  914. # Clear previous trace.
  915. echo '' > trace
  916. # List the available tracers, and pick one.
  917. cat available_tracers
  918. echo function > current_tracer
  919. # List all functions that can be traced
  920. # cat available_filter_functions
  921. # Choose one.
  922. echo __kmalloc >set_ftrace_filter
  923. # Confirm that only __kmalloc is enabled.
  924. cat enabled_functions
  925. echo 1 > tracing_on
  926. # Latest events.
  927. head trace
  928. # Observe trace continously, and drain seen events out.
  929. cat trace_pipe &
  930. ....
  931. Sample output:
  932. ....
  933. # tracer: function
  934. #
  935. # entries-in-buffer/entries-written: 97/97 #P:1
  936. #
  937. # _-----=> irqs-off
  938. # / _----=> need-resched
  939. # | / _---=> hardirq/softirq
  940. # || / _--=> preempt-depth
  941. # ||| / delay
  942. # TASK-PID CPU# |||| TIMESTAMP FUNCTION
  943. # | | | |||| | |
  944. head-228 [000] .... 825.534637: __kmalloc <-load_elf_phdrs
  945. head-228 [000] .... 825.534692: __kmalloc <-load_elf_binary
  946. head-228 [000] .... 825.534815: __kmalloc <-load_elf_phdrs
  947. head-228 [000] .... 825.550917: __kmalloc <-__seq_open_private
  948. head-228 [000] .... 825.550953: __kmalloc <-tracing_open
  949. head-229 [000] .... 826.756585: __kmalloc <-load_elf_phdrs
  950. head-229 [000] .... 826.756627: __kmalloc <-load_elf_binary
  951. head-229 [000] .... 826.756719: __kmalloc <-load_elf_phdrs
  952. head-229 [000] .... 826.773796: __kmalloc <-__seq_open_private
  953. head-229 [000] .... 826.773835: __kmalloc <-tracing_open
  954. head-230 [000] .... 827.174988: __kmalloc <-load_elf_phdrs
  955. head-230 [000] .... 827.175046: __kmalloc <-load_elf_binary
  956. head-230 [000] .... 827.175171: __kmalloc <-load_elf_phdrs
  957. ....
  958. Trace all possible functions, and draw a call graph:
  959. ....
  960. echo 1 > max_graph_depth
  961. echo 1 > events/enable
  962. echo function_graph > current_tracer
  963. ....
  964. Sample output:
  965. ....
  966. # CPU DURATION FUNCTION CALLS
  967. # | | | | | | |
  968. 0) 2.173 us | } /* ntp_tick_length */
  969. 0) | timekeeping_update() {
  970. 0) 4.176 us | ntp_get_next_leap();
  971. 0) 5.016 us | update_vsyscall();
  972. 0) | raw_notifier_call_chain() {
  973. 0) 2.241 us | notifier_call_chain();
  974. 0) + 19.879 us | }
  975. 0) 3.144 us | update_fast_timekeeper();
  976. 0) 2.738 us | update_fast_timekeeper();
  977. 0) ! 117.147 us | }
  978. 0) | _raw_spin_unlock_irqrestore() {
  979. 0) 4.045 us | _raw_write_unlock_irqrestore();
  980. 0) + 22.066 us | }
  981. 0) ! 265.278 us | } /* update_wall_time */
  982. ....
  983. TODO: what do `+` and `!` mean?
  984. Each `enable` under the `events/` tree enables a certain set of functions, the higher the `enable` more functions are enabled.
  985. == QEMU user mode
  986. This has nothing to do with the Linux kernel, but it is cool:
  987. ....
  988. sudo apt-get install qemu-user
  989. ./build -a arm
  990. cd buildroot/output.arm~/target
  991. qemu-arm -L . bin/ls
  992. ....
  993. This uses QEMU's user-mode emulation mode that allows us to run cross-compiled userland programs directly on the host.
  994. 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.
  995. In other words, much cooler than:
  996. ....
  997. arm-linux-gnueabi-gcc -o hello -static hello.c
  998. qemu-arm hello
  999. ....
  1000. 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:
  1001. ....
  1002. package/qemu/qemu.mk:110: *** "Refusing to build qemu-user: target Linux version newer than host's.". Stop.
  1003. ....
  1004. since we are using a bleeding edge kernel, which is a sanity check in the Buildroot QEMU package.
  1005. 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?
  1006. GDB step debugging is also possible with:
  1007. ....
  1008. qemu-arm -g 1234 -L . bin/ls
  1009. ../host/usr/bin/arm-buildroot-linux-uclibcgnueabi-gdb -ex 'target remote localhost:1234'
  1010. ....
  1011. TODO: find source. Lazy now.
  1012. == Snapshot
  1013. https://stackoverflow.com/questions/40227651/does-qemu-emulator-have-checkpoint-function/48724371#48724371
  1014. QEMU allows us to take snapshots at any time through the monitor.
  1015. You can then restore CPU, memory and disk state back at any time.
  1016. qcow2 filesystems must be used for that to work.
  1017. To test it out, login into the VM with and run:
  1018. ....
  1019. /count.sh
  1020. ....
  1021. On another shell, take a snapshot:
  1022. ....
  1023. echo 'savevm my_snap_id' | ./qemumonitor
  1024. ....
  1025. The counting continues.
  1026. Restore the snapshot:
  1027. ....
  1028. echo 'loadvm my_snap_id' | ./qemumonitor
  1029. ....
  1030. and the counting goes back to where we saved. This shows that CPU and memory states were reverted.
  1031. We can also verify that the disk state is also reversed. Guest:
  1032. ....
  1033. echo 0 >f
  1034. ....
  1035. Monitor:
  1036. ....
  1037. echo 'savevm my_snap_id' | ./qemumonitor
  1038. ....
  1039. Guest:
  1040. ....
  1041. echo 1 >f
  1042. ....
  1043. Monitor:
  1044. ....
  1045. echo 'loadvm my_snap_id' | ./qemumonitor
  1046. ....
  1047. Guest:
  1048. ....
  1049. cat f
  1050. ....
  1051. And the output is `0`.
  1052. Our setup does not allow for snapshotting while using <<initrd>>.
  1053. == Educational hardware models
  1054. We have added and interacted with a few educational hardware models in QEMU.
  1055. This is useful to learn:
  1056. * how to create new hardware models for QEMU. Overview: https://stackoverflow.com/questions/28315265/how-to-add-a-new-device-in-qemu-source-code
  1057. * how the Linux kernel interacts with hardware
  1058. To get started, have a look at the "Hardware device drivers" secion under link:kernel_module/README.adoc[], and try to run those modules, and then grep the QEMU source code.
  1059. == gem5
  1060. gem5 is a system simulator, much <<gem5-vs-qemu,like QEMU>>: http://gem5.org/
  1061. For the most part, just add the `-g` option to the QEMU commands and everything should magically work:
  1062. ....
  1063. ./configure && ./build -a arm -g
  1064. ./run -a arm -g
  1065. ....
  1066. On another shell:
  1067. ....
  1068. ./gem5-shell
  1069. ....
  1070. A full rebuild is currently needed even if you already have QEMU working unfortunately, see: <<gem5-and-qemu-with-the-same-kernel-configuration>>
  1071. Tested architectures:
  1072. * `arm`
  1073. * `aarch64`
  1074. * `x86_64`
  1075. Like QEMU, gem5 also has a syscall emulation mode (SE), but in this tutorial we focus on the full system emulation mode (FS). For a comparision see: https://stackoverflow.com/questions/48986597/when-should-you-use-full-system-fs-vs-syscall-emulation-se-with-userland-program
  1076. === gem5 vs QEMU
  1077. * advantages of gem5:
  1078. ** 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:
  1079. *** do much more realistic performance benchmarking with it, which makes absolutely no sense in QEMU, which is purely functional
  1080. *** make certain functional cache observations that are not possible in QEMU, e.g.:
  1081. **** 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.
  1082. **** TODO spectre / meltdown
  1083. +
  1084. It is not of course truly cycle accurate, as that
  1085. ** would require exposing proprietary information of the CPU designs: link:https://stackoverflow.com/questions/17454955/can-you-check-performance-of-a-program-running-with-qemu-simulator/33580850#33580850[]
  1086. ** would make the simulation even slower TODO confirm, by how much
  1087. +
  1088. but the approximation is reasonable.
  1089. +
  1090. It is used mostly for microarchitecture 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.
  1091. ** runs are deterministic by default, unlike QEMU which has a special <<record-and-replay>> mode, that requires first playing the content once and then replaying
  1092. * disadvantage of gem5: slower than QEMU, see: <<gem5-vs-qemu-performance>>
  1093. +
  1094. This implies that the user base is much smaller, since no Android devs.
  1095. +
  1096. 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:
  1097. +
  1098. --
  1099. ** the documentation is more scarce
  1100. ** it takes longer to support new hardware features
  1101. --
  1102. +
  1103. Well, not that AOSP is that much better anyways.
  1104. * not sure: gem5 has BSD license while QEMU has GPL
  1105. +
  1106. This suits chip makers that want to distribute forks with secret IP to their customers.
  1107. +
  1108. On the other hand, the chip makers tend to upstream less, and the project becomes more crappy in average :-)
  1109. ==== gem5 vs QEMU performance
  1110. We have benchmarked a Linux kernel boot at commit da79d6c6cde0fbe5473ce868c9be4771160a003b with the commands:
  1111. ....
  1112. # Try to manually hit Ctrl + C as soon as system shutdown message appears.
  1113. time ./run -a arm -e 'init=/poweroff.out'
  1114. time ./run -a arm -e 'm5 exit' -g
  1115. time ./run -a arm -e 'm5 exit' -g -- --caches --cpu-type=HPI
  1116. time ./run -a x86_64 -e 'init=/poweroff.out'
  1117. time ./run -a x86_64 -e 'init=/poweroff.out' - -enable-kvm
  1118. time ./run -a x86_64 -e 'init=/poweroff.out' -g
  1119. ....
  1120. and the results were:
  1121. [options="header"]
  1122. |===
  1123. |Emulator |Time |N times slower than QEMU
  1124. |QEMU ARM |6 seconds |1
  1125. |gem5 ARM AtomicSimpleCPU |1 minute 40 seconds| 17
  1126. |gem5 ARM HPI |10 minutes |100
  1127. |QEMU X86_64 |4 seconds |1
  1128. |QEMU X86_64 KVM |2 seconds |0.5
  1129. |gem5 X86_64 |5 minutes 30 seconds| 82
  1130. |===
  1131. on a Lenovo P51 laptop with:
  1132. * Intel Core i7-7820HQ Processor (8MB Cache, up to 3.90GHz) (4 cores 8 threads)
  1133. * 32GB(16+16) DDR4 2400MHz SODIMM
  1134. * 512GB SSD PCIe TLC OPAL2
  1135. * Ubuntu 17.10
  1136. === gem5 run benchmark
  1137. OK, this is why we used gem5 in the first place, performance measurements!
  1138. https://stackoverflow.com/questions/48944587/how-to-count-the-number-of-cpu-clock-cycles-between-the-start-and-end-of-a-bench
  1139. Let's benchmark https://en.wikipedia.org/wiki/Dhrystone[Dhrystone] which Buildroot provides:
  1140. ....
  1141. ./gem5-bench dhrystone 1000
  1142. ./gem5-bench -r dhrystone 1000
  1143. ....
  1144. These commands output the approximate number of CPU cycles it took Dhrystone to run.
  1145. It works like this:
  1146. * the first commond boots linux with the default simplified `AtomicSimpleCPU`, and generates a <<gem5-checkpoint,checkpoint>> after the kernel boots and before running the benchmark
  1147. * the second command restores the checkpoint with the more detailed `HPI` CPU model, and runs the benchmark. We don't boot with it because that is much slower.
  1148. ARM employees have just been modifying benchmarking code with instrumentation directly: https://github.com/arm-university/arm-gem5-rsk/blob/aa3b51b175a0f3b6e75c9c856092ae0c8f2a7cdc/parsec_patches/xcompile-patch.diff#L230
  1149. A few imperfections of our benchmarking method are:
  1150. * when we do `m5 resetstats` and `m5 exit`, there is some time passed before the `exec` system call returns and the actual benchmark starts and ends
  1151. * the benchmark outputs to stdout, which means so extra cycles in addition to the actual computation. But TODO: how to get the output to check that it is correct without such IO cycles?
  1152. Those problems should be insignificant if the benchmark runs for long enough however.
  1153. TODO: even if we don't switch to the detailed CPU model, the cycle counts on the original run and the one with checkpoint restore differ slightly. Why? Multiple checkpoint restores give the same results as expected however:
  1154. ....
  1155. ./run -a arm -e 'init=/eval.sh - lkmc_eval="m5 checkpoint;m5 resetstats;dhrystone 1000;m5 exit"' -g
  1156. ./run -a arm -g -- -r 1
  1157. ....
  1158. Now you can play a fun little game with your friends:
  1159. * pick a computational problem
  1160. * make a program that solves the computation problem, and outputs output to stdout
  1161. * write the code that runs the correct computation in the smallest number of cycles possible
  1162. To find out why your program is slow, a good first step is to have a look at the statistics for the run:
  1163. ....
  1164. cat m5out/stats.txt
  1165. ....
  1166. Whenever we run `m5 dumpstats` or `m5 exit`, a section with the following format is added to that file:
  1167. ....
  1168. ---------- Begin Simulation Statistics ----------
  1169. [the stats]
  1170. ---------- End Simulation Statistics ----------
  1171. ....
  1172. ==== gem5 system parameters
  1173. Besides optimizing a program for a given CPU setup, chip developers can also do the inverse, and optimize the chip for a given benchmark!
  1174. The rabbit hole is likely deep, but let's scratch a bit of the surface.
  1175. ===== gem5 number of cores
  1176. ....
  1177. ./run -a arm -c 2 -g
  1178. ....
  1179. Check with:
  1180. ....
  1181. cat /proc/cpuinfo
  1182. getconf _NPROCESSORS_CONF
  1183. ....
  1184. ===== gem5 cache size
  1185. A quick `+./run -g -- -h+` leads us to the options:
  1186. ....
  1187. --caches
  1188. --l1d_size=1024
  1189. --l1i_size=1024
  1190. --l2cache
  1191. --l2_size=1024
  1192. --l3_size=1024
  1193. ....
  1194. But keep in mind that it only affects benchmark performance of the most detailed CPU types:
  1195. [options="header"]
  1196. |===
  1197. |arch |CPU type |caches used
  1198. |X86 |`AtomicSimpleCPU` | no
  1199. |X86 |`DerivO3CPU` | ?*
  1200. |ARM |`AtomicSimpleCPU` | no
  1201. |ARM |`HPI` | yes
  1202. |===
  1203. {empty}*: couldn't test because of:
  1204. * https://stackoverflow.com/questions/49011096/how-to-switch-cpu-models-in-gem5-after-restoring-a-checkpoint-and-then-observe-t
  1205. * https://github.com/gem5/gem5/issues/16
  1206. This has been verified with:
  1207. ....
  1208. m5 resetstats && dhrystone 10000 && m5 dumpstats
  1209. ....
  1210. at commit da79d6c6cde0fbe5473ce868c9be4771160a003b with the following gem5 commands cycle counts:
  1211. ....
  1212. # 11M
  1213. ./run -a arm -g
  1214. ./run -a arm -g -- --caches --l2cache
  1215. # 175M
  1216. ./run -a arm -g -- --caches --l1d_size=1024 --l1i_size=1024 --l2cache --l2_size=1024 --l3_size=1024 --cpu-type=HPI
  1217. # 16M
  1218. ./run -a arm -g -- --caches --l1d_size=1024MB --l1i_size=1024MB --l2cache --l2_size=1024MB --l3_size=1024MB --cpu-type=HPI
  1219. # 20M
  1220. ./run -a x86_64 -g -- --caches --l1d_size=1024 --l2cache --l2_size=1024 --l3_size=1024
  1221. ./run -a x86_64 -g -- --caches --l1d_size=1024MB --l2cache --l2_size=1024MB --l3_size=1024MB
  1222. ....
  1223. Cache sizes can in theory be checked with the methods described at: link:https://superuser.com/questions/55776/finding-l2-cache-size-in-linux[]:
  1224. ....
  1225. getconf -a | grep CACHE
  1226. lscpu
  1227. cat /sys/devices/system/cpu/cpu0/cache/index2/size
  1228. ....
  1229. but for some reason the Linux kernel is not seeing the cache sizes:
  1230. * https://stackoverflow.com/questions/49008792/why-doesnt-the-linux-kernel-see-the-cache-sizes-in-the-gem5-emulator-in-full-sy
  1231. * http://gem5-users.gem5.narkive.com/4xVBlf3c/verify-cache-configuration
  1232. Behaviour breakdown:
  1233. * arm QEMU and gem5 (both `AtomicSimpleCPU` or `HPI`), x86 gem5: `/sys` files don't exist, and `getconf` and `lscpu` value empty
  1234. * x86 QEMU: `/sys` files exist, but `getconf` and `lscpu` values still empty
  1235. ===== gem5 memory latency
  1236. TODO These look promising:
  1237. ....
  1238. --list-mem-types
  1239. --mem-type=MEM_TYPE
  1240. --mem-channels=MEM_CHANNELS
  1241. --mem-ranks=MEM_RANKS
  1242. --mem-size=MEM_SIZE
  1243. ....
  1244. TODO: now to verify this with the Linux kernel? Besides raw performance benchmarks.
  1245. ===== gem5 disk and network latency
  1246. TODO These look promising:
  1247. ....
  1248. --ethernet-linkspeed
  1249. --ethernet-linkdelay
  1250. ....
  1251. and also: `gem5-dist`: https://publish.illinois.edu/icsl-pdgem5/
  1252. ===== gem5 clock frequency
  1253. Clock frequency: TODO how does it affect performance in benchmarks?
  1254. ....
  1255. ./run -a arm -g -- --cpu-clock 10000000
  1256. ....
  1257. Check with:
  1258. ....
  1259. m5 resetstats && sleep 10 && m5 dumpstats
  1260. ....
  1261. and then:
  1262. ....
  1263. grep numCycles m5out/stats.txt
  1264. ....
  1265. TODO: why doesn't this exist:
  1266. ....
  1267. ls /sys/devices/system/cpu/cpu0/cpufreq
  1268. ....
  1269. ==== Enable compiler optimizations
  1270. If you are benchmarking compiled programs instead of hand written assembly, remember that we configure Buildroot to disable optimizations by default with:
  1271. ....
  1272. BR2_OPTIMIZE_0=y
  1273. ....
  1274. to improve the debugging experience.
  1275. You will likely want to change that to:
  1276. ....
  1277. BR2_OPTIMIZE_3=y
  1278. ....
  1279. and do a full rebuild.
  1280. TODO is it possible to compile a single package with optimizations enabled? In any case, this wouldn't be very representative, since calls to an unoptimized libc will also have an impact on performance. Kernel-wise it should be fine though, since the kernel requires `O=2`.
  1281. ==== Interesting benchmarks
  1282. Buildroot built-in libraries, mostly under Libraries > Other:
  1283. * Armadillo `C++`: linear algebra
  1284. * CBLAS / CLAPACK: linear algebra
  1285. * fftw: Fourier transform
  1286. * Eigen: linear algebra
  1287. * Flann
  1288. * GSL: various
  1289. * liblinear
  1290. * libspacialindex
  1291. * libtommath
  1292. * qhull
  1293. There are not yet enabled, but it should be easy to so:
  1294. * enable them in link:buildroot_config_fragment[] and rebuild
  1295. * create a test program that uses each library under link:kernel_module/user[]
  1296. External open source benchmarks. We will try to create Buildroot packages for them, add them to this repo, and potentially upstream:
  1297. * http://parsec.cs.princeton.edu/ Mentioned on docs: http://gem5.org/PARSEC_benchmarks
  1298. * http://www.m5sim.org/Splash_benchmarks
  1299. ===== PARSEC benchmark
  1300. We have ported the PARSEC benchmark http://parsec.cs.princeton.edu for cross compilation at: https://github.com/cirosantilli/parsec-benchmark
  1301. This repo makes it trivial to get started with it:
  1302. ....
  1303. ./build -a arm -g -i buildroot_config_fragment_parsec
  1304. ./run -a arm -g
  1305. ....
  1306. As mentioned at link:https://github.com/cirosantilli/parsec-benchmark[], only SPLASH2 was currently ported.
  1307. Keep in mind that activating PARSEC makes images huge at a few Gigs, specially so since we make multiple images for each configuration for different purposes, e.g. `.ext2`, `.cpio`, etc. This is why we don't build PARSEC by default.
  1308. Once inside the guest, we could in theory launch PARSEC exactly as you would launch it on the host:
  1309. ....
  1310. cd /parsec/
  1311. bash
  1312. . env.sh
  1313. parsecmgmt -a run -p splash2x.fmm -i test
  1314. ....
  1315. TODO: `splash2x.barnes` segfaults on `arsecmgmt -a run -p splash2x.fmm -i simsmall` inside QEMU. Why? Other benchmarks ran fine.
  1316. ....
  1317. [PARSEC] [---------- Beginning of output ----------]
  1318. Generating input file input_1...
  1319. Running /parsec/ext/splash2x/apps/barnes/inst/arm-linux.gcc/bin/barnes 1 < input_1:
  1320. reading input file :
  1321. Segmentation fault
  1322. ....
  1323. However, while this is fine inside QEMU, it is not practical in gem5, since the `parsecmgmt` Bash scripts just takes too long to run in that case!
  1324. So instead, you must find out the raw executable command, and run it manually yourself.
  1325. This command can be found from the `Running` line that `parsecmgmt` outputs when running the programs.
  1326. "Luckily", we run the run scripts while creating the image to extract the inputs, so you can just do a find in your shell history to find the run command and find a line of type:
  1327. ....
  1328. Running /parsec/ext/splash2x/apps/fmm/inst/arm-linux.gcc/bin/fmm 1 < input_1:
  1329. ....
  1330. which teaches you that you can run `fmm` as:
  1331. ....
  1332. cd /parsec/ext/splash2x/apps/fmm/run
  1333. /parsec/ext/splash2x/apps/fmm/inst/arm-linux.gcc/bin/fmm 1 < input_1
  1334. ....
  1335. And so inside of `gem5`, you likely want to do:
  1336. ....
  1337. cd /parsec/ext/splash2x/apps/fmm/run
  1338. m5 checkpoint
  1339. m5 resetstats && /parsec/ext/splash2x/apps/fmm/inst/arm-linux.gcc/bin/fmm 1 < input_1 && m5 dumpstats
  1340. ....
  1341. You will always want to `cd` into the `run` directory first, which is where the input is located.
  1342. ====== PARSEC change the input size
  1343. One limitation is that only one input size is available on the guest for a given build.
  1344. To change that, edit link:buildroot_config_fragment_parsec[] to contain for example:
  1345. ....
  1346. BR2_PACKAGE_PARSEC_BENCHMARK_INPUT_SIZE=simsmall
  1347. ....
  1348. and then rebuild with:
  1349. ....
  1350. ./build -a arm -g -i buildroot_config_fragment_parsec parsec-benchmark-reconfigure
  1351. ....
  1352. This limitation exists because `parsecmgmt` generates the input files just before running, but we can't run on gem5 as it is too slow!
  1353. One option would be to do that inside the guest with QEMU, but this would required a full rebuild due to <<gem5-and-qemu-with-the-same-kernel-configuration>>.
  1354. Also, we can't generate all input sizes at once, because many of them have the same name and would overwrite one another... Parsec clearly needs a redesign for embedded, maybe we will patch it later.
  1355. ====== PARSEC uninstall
  1356. If you want to remove PARSEC later, Buildroot doesn't provide an automated package removal mechanism as documented at: link:https://github.com/buildroot/buildroot/blob/2017.08/docs/manual/rebuilding-packages.txt#L90[], but the following procedure should be satisfactory:
  1357. ....
  1358. rm -rf \
  1359. ./buildroot/dl/parsec-* \
  1360. ./buildroot/output.arm-gem5~/build/parsec-* \
  1361. ./buildroot/output.arm-gem5~/images/rootfs.* \
  1362. ./buildroot/output.arm-gem5~/target/parsec-* \
  1363. ;
  1364. ./build -a arm -g
  1365. ....
  1366. ====== PARSEC benchmark hacking
  1367. If you end up going inside link:parsec/parsec[] to hack up the benchmark (you will!), these tips will be helpful.
  1368. Buildroot was not designed to deal with large images, and currently cross rebuilds are a bit slow, due to some image generation and validation steps.
  1369. A few workarounds are:
  1370. * develop in host first as much as you can. Our PARSEC fork supports it.
  1371. +
  1372. If you do this, don't forget to do a:
  1373. +
  1374. ....
  1375. cd parsec-benchmark/parsec-benchmark
  1376. git clean -xdf .
  1377. ....
  1378. before going for the cross compile build.
  1379. +
  1380. * patch Buildroot to work well, and keep cross compiling all the way. This should be totally viable, and we should do it.
  1381. +
  1382. Don't forget to explicitly rebuild PARSEC with:
  1383. ....
  1384. ./build -a arm -g -i buildroot_config_fragment_parsec parsec-benchmark-reconfigure
  1385. ....
  1386. +
  1387. You may also want to test if your patches are still functionally correct inside of QEMU first, which is a faster emulator.
  1388. +
  1389. * sell your soul, and compile natively inside the guest. We won't do this, not only because it is evil, but also because Buildroot explicitly does not support it: https://buildroot.org/downloads/manual/manual.html#faq-no-compiler-on-target ARM employees have been known to do this: https://github.com/arm-university/arm-gem5-rsk/blob/aa3b51b175a0f3b6e75c9c856092ae0c8f2a7cdc/parsec_patches/qemu-patch.diff
  1390. TODO Buildroot is slow because of the `pkg-generic` `GLOBAL_INSTRUMENTATION_HOOKS` sanitation which go over the entire tree doing complex operations... I no like, in particular `check_bin_arch` and `check_host_rpath`.
  1391. The pause is followed by:
  1392. ....
  1393. buildroot/output.arm~/build/parsec-benchmark-custom/.stamp_target_installed
  1394. ....
  1395. so which shows that the whole delay is inside our install itself.
  1396. I put an `echo f` in `check_bin_arch`, and it just loops forever, does not stop on a particular package.
  1397. === gem5 kernel command line parameters
  1398. Analogous <<kernel-command-line-parameters,to QEMU>>:
  1399. ....
  1400. ./run -a arm -e 'init=/poweroff.out' -g
  1401. ....
  1402. Internals: when we give `--command-line=` to gem5, it overrides default command lines, including some mandatory ones which are required to boot properly.
  1403. Our run script hardcodes the require options in the default `--command-line` and appends extra options given by `-e`.
  1404. To find the default options in the first place, we removed `--command-line` and ran:
  1405. ....
  1406. ./run -a arm -g
  1407. ....
  1408. and then looked at the line of the Linux kernel that starts with:
  1409. ....
  1410. Kernel command line:
  1411. ....
  1412. [[gem5-gdb]]
  1413. === gem5 GDB step debugging
  1414. Analogous <<gdb,to QEMU>>, on the first shell:
  1415. ....
  1416. ./run -a arm -d -g
  1417. ....
  1418. On the second shell:
  1419. ....
  1420. ./rungdb -a arm -g
  1421. ....
  1422. This makes the VM stop, so from inside GDB:
  1423. ....
  1424. continue
  1425. ....
  1426. On a third shell:
  1427. ....
  1428. ./gem5-shell
  1429. ....
  1430. And we now see the boot messages, and then get a shell. Now try the `/continue.sh` procedure described for QEMU.
  1431. TODO: how to stop at `start_kernel`? gem5 listens for GDB by default, and therefore does not wait for a GDB connection to start like QEMU does. So when GDB connects we might have already passed `start_kernel`. Maybe `--debug-break=0` can be used?
  1432. === gem5 checkpoint
  1433. Analogous to QEMU's <<snapshot>>, but better since it can be started from inside the guest, so we can easily checkpoint after a specific guest event, e.g. just before `init` is done.
  1434. Documentation: http://gem5.org/Checkpoints
  1435. ....
  1436. ./rung -a arm -g
  1437. ....
  1438. In guest, wait for the boot to end and run:
  1439. ....
  1440. m5 checkpoint
  1441. ....
  1442. To restore the checkpoint, kill the VM and run:
  1443. ....
  1444. ./rung -a arm -g -- -r 1
  1445. ....
  1446. Let's create a second checkpoint to see how it works, in guest:
  1447. ....
  1448. date >f
  1449. m5 checkpoint
  1450. ....
  1451. Kill the VM, and try it out:
  1452. ....
  1453. ./run -a arm -g -- -r 2
  1454. ....
  1455. and now in the guest:
  1456. ....
  1457. cat f
  1458. ....
  1459. contains the `date`. The file `f` wouldn't exist had we used the first checkpoint with `-r 1`.
  1460. Internals:
  1461. * the checkpoints are stored under `m5out/cpt.*`
  1462. * `m5` is a guest utility present inside the gem5 tree which we cross-compiled and installed into the guest
  1463. If you automate things with <<kernel-command-line-parameters>> as in:
  1464. ....
  1465. ./run -a arm -e 'init=/eval.sh - lkmc_eval="m5 checkpoint;m5 resetstats;dhrystone 1000;m5 exit"' -g
  1466. ....
  1467. Then there is no need to pass the kernel command line again to gem5 for replay:
  1468. ....
  1469. ./run -a arm -g -- -r 1
  1470. ....
  1471. since boot has already happened, and the parameters are already in the RAM of the snapshot.
  1472. ==== gem5 restore checkpoint with a different CPU
  1473. gem5 can switch to a different CPU model when restoring a checkpoint.
  1474. A common combo is to boot Linux with a fast CPU, make a checkpoint and then replay the benchmark of interest with a slower CPU.
  1475. An illustrative interactive run:
  1476. ....
  1477. ./run -a arm -g
  1478. ....
  1479. In guest:
  1480. ....
  1481. m5 checkpoint
  1482. ....
  1483. And then restore the checkpoint with a different CPU:
  1484. ....
  1485. ./run -a arm -g -- --caches -r 1 --restore-with-cpu=HPI
  1486. ....
  1487. === Pass extra options to gem5
  1488. Pass options to the `fs.py` script:
  1489. * get help:
  1490. +
  1491. ....
  1492. ./run -g -- -h
  1493. ....
  1494. * boot with the more detailed and slow `HPI` CPU model:
  1495. +
  1496. ....
  1497. ./run -a arm -g -- --caches --cpu-type=HPI
  1498. ....
  1499. Pass options to the `gem5` executable itself:
  1500. * get help:
  1501. +
  1502. ....
  1503. ./run -G '-h' -g
  1504. ....
  1505. === Run multiple gem5 instances at once
  1506. gem5 just assigns new ports if some ports are occupied, so we can do:
  1507. ....
  1508. ./run -g
  1509. # Same as ./gem5-shell 0
  1510. ./gem5-shell
  1511. ....
  1512. And a second instance:
  1513. ....
  1514. ./run -g
  1515. ./gem5-shell 1
  1516. ....
  1517. TODO Now we just need to network them up to have some more fun! See dist-gem5: http://publish.illinois.edu/icsl-pdgem5/
  1518. === gem5 and QEMU with the same kernel configuration
  1519. We would like to be able to run both gem5 and QEMU with the same kernel build to avoid duplication, but TODO we haven't been able to get that working yet.
  1520. This documents our failed attempts so far.
  1521. As a result, we currently have to create two full `buildroot/output*` directories, which means two full GCC builds.
  1522. ==== QEMU with gem5 kernel configuration
  1523. To test this, hack up `run` to use the `buildroot/output.arm-gem5~` directory, and then run:
  1524. ....
  1525. ./run -a arm
  1526. ....
  1527. Now QEMU hangs at:
  1528. ....
  1529. audio: Could not init `oss' audio driver
  1530. ....
  1531. and the display shows:
  1532. ....
  1533. Guest has not initialized the display (yet).
  1534. ....
  1535. ==== gem5 with QEMU kernel configuration
  1536. Test it out with:
  1537. ....
  1538. ./run -a arm -g
  1539. ....
  1540. TODO hangs at:
  1541. ....
  1542. **** REAL SIMULATION ****
  1543. warn: Existing EnergyCtrl, but no enabled DVFSHandler found.
  1544. info: Entering event queue @ 0. Starting simulation...
  1545. 1614868500: system.terminal: attach terminal 0
  1546. ....
  1547. and the `telnet` at:
  1548. ....
  1549. 2017-12-28-11-59-51@ciro@ciro-p51$ ./gem5-shell
  1550. Trying 127.0.0.1...
  1551. Connected to localhost.
  1552. Escape character is '^]'.
  1553. ==== m5 slave terminal: Terminal 0 ====
  1554. ....
  1555. I have also tried to copy the exact same kernel command line options used by QEMU, but nothing changed.
  1556. === gem5 limitations
  1557. * networking not working. We currently just disable it from `inittab` by default to prevent waiting at startup
  1558. * `gdbserver`: https://stackoverflow.com/questions/48941494/how-to-do-port-forwarding-from-guest-to-host-in-gem5
  1559. ==== gem5 x86_64 limitations
  1560. * `gdb` debugging not working. First we need to remove the initial `set arch i386:x86-64:intel` required for QEMU. Then it cannot find the symbols.
  1561. == Failed action
  1562. === Record and replay
  1563. 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.
  1564. 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
  1565. 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?
  1566. == Insane action
  1567. === Run on host
  1568. 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.
  1569. It has however severe limitations, and you will soon see that the compilation time and disk usage are well worth it:
  1570. * 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].
  1571. * bugs can easily break you system. E.g.:
  1572. ** segfaults can trivially lead to a kernel crash, and require a reboot
  1573. ** 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`
  1574. ** 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]
  1575. * can't control which hardware is used, notably the CPU architecture
  1576. * can't step debug it with GDB easily
  1577. Still interested?
  1578. ....
  1579. cd kernel_module
  1580. ./make-host.sh
  1581. ....
  1582. 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:
  1583. ....
  1584. mv broken.c broken.c~
  1585. ./build_host
  1586. ....
  1587. Once you manage to compile, and have come to terms with the fact that this may blow up your host, try it out with:
  1588. ....
  1589. sudo insmod hello.ko
  1590. # Our module is there.
  1591. sudo lsmod | grep hello
  1592. # Last message should be: hello init
  1593. dmest -T
  1594. sudo rmmod hello
  1595. # Last message should be: hello exit
  1596. dmesg -T
  1597. # Not present anymore
  1598. sudo lsmod | grep hello
  1599. ....
  1600. === Hello host
  1601. Minimal host build system sanity check example.
  1602. ....
  1603. cd hello_host
  1604. make
  1605. insmod hello.ko
  1606. dmesg
  1607. rmmod hello.ko
  1608. dmesg
  1609. ....
  1610. == Conversation
  1611. === kmod
  1612. Multi-call executable that implements: `lsmod`, `insmod`, `rmmod`, and other tools on desktop distros such as Ubuntu 16.04, where e.g.:
  1613. ....
  1614. ls -l /bin/lsmod
  1615. ....
  1616. gives:
  1617. ....
  1618. lrwxrwxrwx 1 root root 4 Jul 25 15:35 /bin/lsmod -> kmod
  1619. ....
  1620. and:
  1621. ....
  1622. dpkg -l | grep -Ei
  1623. ....
  1624. contains:
  1625. ....
  1626. ii kmod 22-1ubuntu5 amd64 tools for managing Linux kernel modules
  1627. ....
  1628. BusyBox also implements its own version of those executables. There are some differences.
  1629. Buildroot also has a kmod package, but we are not using it since BusyBox' version is good enough so far.
  1630. This page will only describe features that differ from kmod to the BusyBox implementation.
  1631. Source code: https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git
  1632. ==== module-init-tools
  1633. Name of a predecessor set of tools.
  1634. ==== modprobe
  1635. Load module under different name to avoid conflicts:
  1636. ....
  1637. sudo modprobe vmhgfs -o vm_hgfs
  1638. ....
  1639. === Device tree
  1640. `platform_device.c` together with its kernel and QEMU forks contains a minimal runnable example.
  1641. Good format descriptions:
  1642. * https://www.raspberrypi.org/documentation/configuration/device-tree.md
  1643. Minimal example
  1644. ....
  1645. /dts-v1/;
  1646. / {
  1647. a;
  1648. };
  1649. ....
  1650. Check correctness with:
  1651. ....
  1652. dtc a.dts
  1653. ....
  1654. Separate nodes are simply merged by node path, e.g.:
  1655. ....
  1656. /dts-v1/;
  1657. / {
  1658. a;
  1659. };
  1660. / {
  1661. b;
  1662. };
  1663. ....
  1664. then `dtc a.dts` gives:
  1665. ....
  1666. /dts-v1/;
  1667. / {
  1668. a;
  1669. b;
  1670. };
  1671. ....
  1672. === Directory structure
  1673. :leveloffset: +3
  1674. include::buildroot_patches/README.adoc[]
  1675. include::global_patch_dir/README.adoc[]
  1676. include::kernel_module/README.adoc[]
  1677. include::kernel_module/user/README.adoc[]
  1678. include::rootfs_overlay/README.adoc[]
  1679. :leveloffset: -3
  1680. === Maintainers
  1681. :leveloffset: +3
  1682. include::CONTRIBUTING.adoc[]
  1683. :leveloffset: -3
  1684. ==== How to update the Linux kernel?
  1685. ....
  1686. # Last point before out patches.
  1687. last_mainline_revision=v4.14
  1688. next_mainline_revision=v4.15
  1689. cd linux
  1690. # Create a branch before the rebase.
  1691. git branch "lkmc-${last_mainline_revision}"
  1692. git remote set-url origin git@github.com:cirosantilli/linux.git
  1693. git push
  1694. git remote add up git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
  1695. git fetch up
  1696. git rebase --onto "$next_mainline_revision" "$last_mainline_revision"
  1697. ./build -l
  1698. # Manually fix our kernel modules if necessary.
  1699. cd ..
  1700. git branch "buildroot-2017.08-linux-${last_mainline_revision}"
  1701. git add .
  1702. git commit -m "Linux ${next_mainline_revision}"
  1703. git push
  1704. ....
  1705. and update the README!
  1706. During update all you kernel modules may break since the kernel API is not stable.
  1707. They are usually trivial breaks of things moving around headers or to sub-structs.
  1708. The userland, however, should simply not break, as Linus enforces strict backwards compatibility of userland interfaces.
  1709. This backwards compatibility is just awesome, it makes getting and running the latest master painless.
  1710. This also makes this repo the perfect setup to develop the Linux kernel.
  1711. ==== How to downgrade the Linux kernel?
  1712. 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.
  1713. The default Linux kernel version is bumped in Buildroot with commit messages of type:
  1714. ....
  1715. linux: bump default to version 4.9.6
  1716. ....
  1717. So you can try:
  1718. ....
  1719. git log --grep 'linux: bump default to version'
  1720. ....
  1721. Those commits change `BR2_LINUX_KERNEL_LATEST_VERSION` in `/linux/Config.in`.
  1722. 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.
  1723. ==== How to add new Buildroot options?
  1724. ....
  1725. cd buildroot/output.x86_64~
  1726. make menuconfig
  1727. ....
  1728. Hit `/` and search for the settings.
  1729. Save and quit.
  1730. ....
  1731. diff .config.olg .config
  1732. ....
  1733. Copy and paste the diff additions to `buildroot_config_fragment`.
  1734. ==== What is making my build so slow?
  1735. ....
  1736. cd buildroot/output.x86_64~
  1737. make graph-build
  1738. xdg-open graphs/build.pie-packages.pdf
  1739. ....
  1740. Our philosophy is:
  1741. * if something adds little to the build time, build it in by default
  1742. * otherwise, make it optional
  1743. === About
  1744. This project is for people who want to learn and modify low level system components:
  1745. * Linux kernel and Linux kernel modules
  1746. * full systems emulators like QEMU and gem5
  1747. * C standard libraries. This could also be put on a submodule if people show interest.
  1748. * Buildroot. We use and therefore document, a large part of its feature set.
  1749. Philosophy:
  1750. * automate as much as possible to make things more reproducible
  1751. * do everything from source to make things understandable and hackable
  1752. This project should be called "Linux kernel playground", like: https://github.com/Fuzion24/AndroidKernelExploitationPlayground maybe I'll rename it some day. Would semi conflict with: http://copr-fe.cloud.fedoraproject.org/coprs/jwboyer/kernel-playground/ though.
  1753. History:
  1754. ____
  1755. Once upon a time, there was a boy called Linus. Linus made a super fun toy, and since he was not very humble, decided to call it Linux.
  1756. Linux was great, but it had one big problem: it was very difficult to learn how to play with it!
  1757. As a result, only some weird kids who were very bored ended up playing with Linux, and everyone thought those kids were very cool, in their own weird way.
  1758. One day, a mysterious new kid called Ciro tried to play with Linux, and like many before him, got very frustrated, and gave up.
  1759. A few years later, Ciro had grown up a bit, and by chance came across a very cool toy made by the boy Petazzoni and his gang: it was called Buildroot.
  1760. Ciro noticed that if you used Buildroot together with Linux, Linux suddenly became very fun to play with!
  1761. So Ciro decided to explain to as many kids as possible how to use Buildroot to play with Linux, and everyone was happy.
  1762. THE END
  1763. ____
  1764. === Bibliography
  1765. Runnable stuff:
  1766. * 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.
  1767. * https://github.com/satoru-takeuchi/elkdat manual build process without Buildroot, very few and simple kernel modules
  1768. * https://github.com/tinyclub/linux-lab Buildroot based, no kernel modules?
  1769. * https://github.com/agelastic/eudyptula
  1770. * 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/
  1771. * 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 (2 hours build vs 30 minutes), Android is Linux based, and QEMU is the emulator backend. These instructions might work for debugging the kernel: https://github.com/Fuzion24/AndroidKernelExploitationPlayground
  1772. Theory:
  1773. * 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.
  1774. * https://balau82.wordpress.com awesome low level resource
  1775. * https://lwn.net
  1776. * http://www.makelinux.net