index.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8"/>
  5. <title>Interim OS 2015</title>
  6. <style>
  7. body {
  8. margin: 50px;
  9. max-width: 600px;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <pre>
  15. _ _ _
  16. |_|___| |_ ___ ___|_|_____ ___ ___
  17. | | | _| -_| _| | | | . |_ -|
  18. |_|_|_|_| |___|_| |_|_|_|_| |___|___|
  19. </pre>
  20. <p>
  21. Welcome to <a href="https://github.com/mntmn/interim">Interim OS</a>, a minimal operating system featuring a language oriented kernel. (Last Update: 2015-09-10)
  22. </p>
  23. <p>
  24. <ul>
  25. <li><a href="./interim-0.1.0-rpi2.tgz">Download Interim OS Release 0.1.0 (alpha) for Raspberry Pi 2</a></li>
  26. <li><a href="https://github.com/mntmn/interim">Full Source Code at Github</a></li>
  27. </ul>
  28. </p>
  29. <img src="http://dump.mntmn.com/interim-paper/illustrations_small/3254_overview_front_bw.jpg" width="300">
  30. <p>
  31. It is intended for:
  32. <ul>
  33. <li>Computer / OS design education</li>
  34. <li>Embedded systems development</li>
  35. <li>"Recreational" computing / hacking / tinkering</li>
  36. </ul>
  37. <h1>What I Learned Writing an Operating System (and Building a Keyboard)</h1>
  38. <h2>Roots, Bloody Roots</h2>
  39. <p>I don't recall the exact moment when I decided to start the project that turned out to be much, much more work and patience then I ever expected, but it must have been around 1 or 2 years ago.</p>
  40. <p>It has its roots in my experiments with turning AVR-based microcontrollers (Arduino, Teensy) into something resembling a PC or terminal. Back then, the first step was that I tried to generate a VGA signal and display characters on a VGA monitor directly from the MCU without specialized "graphics hardware". Surprisingly, after a lot of glitches and noise, it worked. I connected the pins of an old PS/2 keyboard to the same MCU and a few lines of code later, I could type letters on the screen and had a minimal command line. These early little successes gave me a lot of motivation. </p>
  41. <p><em>When entering new territory, first make small attempts at something you never did before to get some first feelings of success.</em></p>
  42. <p>When I moved to the Teensy, this was my first hands-on encounter with an ARM processor; although I quickly found out that it doesn't really understand the ARM instruction set, but a mini version of it called Thumb. I pasted some code into my bare-bones character generator that could disassemble Thumb, and later wrote a very basic text editor in C that had an "assemble" function that generated Thumb code from assembler source. It didn't support all opcodes, nor macros or other fancy assembler features, but it worked. I soldered an SD card directly to this little computer and linking Arduino's SDFat library, I could read and write files! Later I found out that I could generate up to 256 colors by constructing a resistor ladder that would turn 8 output bits into blazing RRGGGBB encoded pixels, and a similar approach works for 8-bit sound. I spent some nights programming rotating 3D cubes, loading pixel images from SD and even streaming music from a WAV file. It was good. This "bare metal" kind of directness was what I had been missing from computers since the end of the C64 and Amiga times. </p>
  43. <p>But it was extremely limited because MCUs typically only have a few kilobytes (!) of RAM. Very fast, on-die SRAM, but most have something like 8, 16 or (Teensy 3.1) 64kB. Not enough to store a display framebuffer in a satisfying resolution (>320x256). Also, MCUs typically operate at speeds of less than 100 MHz.</p>
  44. <p>Since these experiments, I really craved a computer system that was dead simple, "brutal" and direct, but at the same time in the GHz/GB arena so that I could manipulate interesting audiovisual content and make use of the internet in a meaningful way.</p>
  45. <p>I still haven't found a system like that, but I have an approximation.</p>
  46. <h2>A Simpler OS</h2>
  47. <p>At the same time, I had a nagging feeling that I wanted a simpler operating system that had less layers between me and the hardware, and whose complexity was low enough so someone with limited time could wrap their head around it and become productive quickly. By productive I mean "get graphics and text on the screen, sound from the speakers and packets on the network" and not "run 100 mysterious background services, fill your RAM with a bloated office package and load advertising from the web". </p>
  48. <p>I figured I needed a few components to make the system do something interesting:</p>
  49. <ol>
  50. <li>Load my code and make it run (setup)</li>
  51. <li>Get a pointer to the display contents so I can put pixels on the screen (framebuffer)</li>
  52. <li>Load stuff – like a font – from disk so I can display text (filesystem)</li>
  53. <li>Receive characters from a keyboard</li>
  54. <li>Have some kind of main loop that interprets keyboard input as commands (a REPL)</li>
  55. <li>Write data to a disk</li>
  56. <li>Receive and send packets from/to ethernet (network)</li>
  57. </ol>
  58. <p>The platform I chose to implement these things was the Raspberry Pi 2 (actually first the Pi 1 because I had several lying around, but this is a differnt story). The Raspberry Pi 2 fulfills, in theory, mostly, the requirements I had for the hardware:</p>
  59. <ul>
  60. <li>(almost) 1 GHz RISC CPU (actually <em>four</em> of them + "QPU")</li>
  61. <li>1 GB RAM</li>
  62. <li>Full-HD graphics output</li>
  63. <li>Stereo CD quality audio output</li>
  64. <li>"bare-metal" programmable</li>
  65. </ul>
  66. <p>What I dislike about the RPi 2:</p>
  67. <ul>
  68. <li>Requires closed-source binary blobs to boot</li>
  69. <li>Un(der)documented Videocore IV "QPU" has boot control of system. ARM CPU is a peripheral device</li>
  70. <li>Unnecessary features on the board (MIPI, CSI) that seem like left-overs from mobile SoC</li>
  71. <li>Ethernet is an internal USB device; USB is overly complex</li>
  72. <li>After working with it intensively for several months, it doesn't seem at all like a "clean and simple" system to me</li>
  73. <li>More detailled criticism at https://wiki.debian.org/RaspberryPi</li>
  74. </ul>
  75. <h2>Bare-Metal Setup (RPi2)</h2>
  76. <p>Loading a bare-metal kernel on the RPi 2 is relatively easy. You put a file "kernel7.img" on the first FAT partition of an MBR partioned SD card. You also put the required binary blobs and a "config.txt" file on the card. Then you plug it in and pray. </p>
  77. <p>How do you create a "kernel" file?</p>
  78. <p>kernel7.img is an ARM binary file that you can generate from an ELF executable using objcopy from the ARM version of GNU binutils:</p>
  79. <pre><code>arm-none-eabi-objcopy build/interim-arm.elf -O binary build/kernel7.img
  80. </code></pre>
  81. <p>The secret sauce in the RPi2 loads your binary not at address 0x0, but at address 0x8000. To make everything work, if you compile your binary with GCC, for example, you need a linker file (a file with the extension .ld, passed to gcc with the -T parameter) like this that specifies the start address at the right place:</p>
  82. <pre><code>ENTRY(_start)
  83. SECTIONS
  84. {
  85. . = 0x8000;
  86. .text : {
  87. KEEP(*(.text.boot))
  88. *(.text)
  89. }
  90. .rodata : {
  91. *(.rodata)
  92. }
  93. .data : {
  94. *(.data)
  95. }
  96. .bss : {
  97. _bss_start = ALIGN(4096);
  98. bss = ALIGN(4096);
  99. *(.bss)
  100. }
  101. _bss_end = .;
  102. }
  103. </code></pre>
  104. <p>Linker files look weird, no? Some lessons I learned here:</p>
  105. <ul>
  106. <li>.text is the section that contains your actual machine code</li>
  107. <li>.rodata and .data contain constants like constant numbers and strings</li>
  108. <li>.bss contains non-stack variables that must be initialized to zero at program startup (you have to do this by yourself, or you will get weird behaviour because of randomly initialized variables)</li>
  109. </ul>
  110. <p>If your kernel is written in a high level language like C, this language needs some setup before code written in it can run reliably on the target platform. Which is at least:</p>
  111. <ul>
  112. <li>Clear (zero) the .bss section (see above)</li>
  113. <li>Set up a stack (without a stack, function calls in C will crash)</li>
  114. </ul>
  115. <p>Usually, and I also did it like this, you do this setup in an assembler fragment that is linked in at the start address of your kernel. This performs the critical setup -- on the way probably switching on some CPU features -- and then jump to the "main" function of your C code; then you are in C-land.</p>
  116. <p>How to set up the stack?</p>
  117. <p>Setting up the stack requires you to think about the general memory layout of the system. I decided to have a flat memory layout (virtual addresses = physical addresses, to avoid indirection / knots in my brain) and make the stack and heap (memory that is allocated by the language; explanation further down below) grow in opposite direction from each other.</p>
  118. <p>I did it like this:</p>
  119. <ul>
  120. <li>The heap ("main working memory") starts at 0x1000000, which is 16 MB, and allocations grow the heap with increasing addresses.</li>
  121. <li>The stack (a temporary storage used mainly for function calls) starts at 0xfffffc, which is 4 bytes (1 word = size of a 32-bit pointer) below the heap and grows "down". This means for every new item on the stack, the pointer to the stack (SP) is decremented by 4.</li>
  122. <li>The kernel code and data occupy the first MB of RAM (so the stack cannot be larger than 15 MB, or it would overwrite the kernel).</li>
  123. </ul>
  124. <p>What else to do in the assembler setup fragment?</p>
  125. <ul>
  126. <li><p>Switch on VFP/NEON, the floating point and vector units of the ARM, respectively. Without this, if you use any floating point code, the CPU will crash and you will wonder why.</p></li>
  127. <li><p>In the ARM Architecture Reference Manual (ARM ARM), they also set up the MMU (memory management unit) in assembler, but I found this too cumbersome and adapted mvrn's C code to do this instead.</p></li>
  128. </ul>
  129. <p>Most hardware configuration that is ARM-related, like switching on the VFP, is done via the MRC and MCR instructions. First you read from the control/coprocessor registers using MRC to a temporary register, then you twiddle the bits and then you write everything back with MCR. Example:</p>
  130. <pre><code>mrc p15, #0, r1, c1, c0, #2
  131. orr r1, r1, #(0xf &lt;&lt; 20)
  132. mcr p15, #0, r1, c1, c0, #2
  133. </code></pre>
  134. <h2>Setup in the kernel</h2>
  135. <pre><code>ldr r3, =main // load address of main to R3
  136. blx r3 // branch to R3 and store PC in link register
  137. </code></pre>
  138. <p>The main() function does more hardware configuration:</p>
  139. <ul>
  140. <li>UART, the "serial port", so we can do early debug printing over the serial line, and see what is going on during boot (invaluable!)</li>
  141. <li>MMU, the memory management unit, a complicated topic that helped me boost performace by 100x or so (and I discovered it very late)</li>
  142. <li>QPU, the 3D/shader "quad" processor</li>
  143. <li>Framebuffer address (graphics output)</li>
  144. <li>USB (I integrated parts of the "USPi" library for this)</li>
  145. <li>USB keyboard</li>
  146. <li>USB ethernet</li>
  147. </ul>
  148. <p>Then I launch the REPL, which is the system's main loop.</p>
  149. <h2>Setup in the REPL</h2>
  150. <ul>
  151. <li>Init the compiler (which in turn inits the allocator, which is necessary to allocate Interim Lisp objects on the heap)</li>
  152. <li>Mount filesystems (like /framebuffer, /keyboard, /console, /mouse, /sound and /sd, the SD card interface)</li>
  153. </ul>
  154. <p>Finally, the parts of the OS written in Interim Lisp are loaded by evaluating:</p>
  155. <pre><code>(eval (read (recv (open "/sd/shell.l"))))
  156. </code></pre>
  157. <h2>Reader</h2>
  158. <p>File: reader.c</p>
  159. <p>The Reader parses ASCII/UTF-8 strings into S-Expressions, which are internally represented as trees of the Cell struct (defined in minilisp.h).</p>
  160. <p>A Cell consists of 3 machine words: value/addr (CAR), size/next (CDR) and the tag, which specifies the type of the Cell.</p>
  161. <pre><code>typedef struct Cell {
  162. union {
  163. jit_word_t value;
  164. void* addr;
  165. };
  166. union {
  167. jit_word_t size;
  168. void* next;
  169. };
  170. jit_word_t tag;
  171. } Cell;
  172. </code></pre>
  173. <h2>Allocator</h2>
  174. <p>Carves cells from the heap.</p>
  175. <pre><code>Cell* cell_alloc() {
  176. if (free_list_avail&gt;free_list_consumed) {
  177. // serve from free list
  178. int idx = free_list_consumed;
  179. free_list_consumed++;
  180. Cell* res = free_list[idx];
  181. return res;
  182. } else {
  183. // grow heap
  184. Cell* res = &amp;cell_heap[cells_used];
  185. cells_used++;
  186. if (cells_used&gt;MAX_CELLS) {
  187. // out of memory
  188. printf("[cell_alloc] failed: MAX_CELLS used.\n");
  189. exit(1);
  190. }
  191. return res;
  192. }
  193. }
  194. </code></pre>
  195. <h2>Compiler</h2>
  196. <p>File: compiler.c</p>
  197. <ul>
  198. <li>Opcode list</li>
  199. <li>Function signatures</li>
  200. </ul>
  201. <h2>JIT</h2>
  202. <p>File: jit<em>arm</em>raw.c</p>
  203. <p>Generates ARM instructions.</p>
  204. <pre><code>void jit_movr(int dreg, int sreg) {
  205. uint32_t op = 0xe1a00000;
  206. op |= (sreg&lt;&lt;0);
  207. op |= (dreg&lt;&lt;12);
  208. code[code_idx++] = op;
  209. }
  210. </code></pre>
  211. <h2>Execute</h2>
  212. <h2>Writer</h2>
  213. <p>File: writer.c</p>
  214. <p>Turns Cell trees into human- (and Reader-) readable strings.</p>
  215. <h2>Garbage Collector</h2>
  216. <p>File: alloc.c</p>
  217. <ul>
  218. <li>Mark and sweep</li>
  219. </ul>
  220. <p>Finds all reachable objects and frees the rest.</p>
  221. <h2>"Multitasking"</h2>
  222. <p>Interim is single-tasked. Cooperative multi-tasking is emulated by round-robin executing a list of functions in the global <em>tasks</em> list. Tasks can be spawned by appending a function to this list.</p>
  223. <h2>MMU/L1/L2 Caches setup</h2>
  224. <h2>QPU/3D graphics setup</h2>
  225. <h2>Filesystem: /framebuffer</h2>
  226. <h2>Filesystem: /keyboard</h2>
  227. <h2>Filesystem: /mouse</h2>
  228. <pre><code>(def mouse (open "/mouse"))
  229. (let mouse-info (recv mouse))
  230. (def mouse-dx (car (car mouse-info)))
  231. (def mouse-dy (cdr (car mouse-info)))
  232. </code></pre>
  233. <h2>Filesystem: /sound</h2>
  234. <h2>Filesystem: /sd</h2>
  235. <h2>Filesystem: /net</h2>
  236. <pre><code>(def freenode (open "/net/tcp/62.231.75.133/6667"))
  237. (let packet (recv net))
  238. (if (size packet) (do
  239. ))
  240. </code></pre>
  241. <h2>Interim Lisp</h2>
  242. <p>Interim's syntax is defined as follows.</p>
  243. <p>An atom is one of the following:</p>
  244. <ul>
  245. <li>an integer: 1234</li>
  246. <li>an ASCII symbol: hello</li>
  247. <li>a UTF-8 string: "こんにちは"</li>
  248. <li>a hexadecimal byte string: [deadbeef01020304]</li>
  249. <li>a pair: (123 . 456)</li>
  250. <li>a "lambda", which is an applicable function</li>
  251. <li>nothing</li>
  252. </ul>
  253. <p>A pair is a link between two atoms; it has a left-hand side (traditionally called "car", "contents of address register") and a right-hand side (traditionally called "cdr", "contents of data register").</p>
  254. <p>A list atom is a pair whose left side points to an atom of any type and whose right side points to the next list atom or an "empty list" atom (a pair of two "nothings"). Lists are entered and displayed simply by separating atoms with whitespace and wrapping the result in parentheses: (1 2 3 4).</p>
  255. <p>Interim programs are simply Interim lists. The first item of a progam list must be the symbol of the function to apply to the following parameters; the remaining items of the list are the parameters:</p>
  256. <pre><code>(+ 1 2) ; evaluates to 3.
  257. (- 5 4) ; evaluates to 1.
  258. (def a 23) ; evaluates to 23. as a side-effect, the symbol "a" is defined as the number 23.
  259. (def double (fn x (+ x x))) ; defines the function "double" that takes one parameter called "x"
  260. (double a) ; now evaluates to 46.
  261. </code></pre>
  262. <p>A number of built-in symbols are available at system startup.</p>
  263. <h2>Symbol definition and functions</h2>
  264. <pre><code>(def &lt;symbol&gt; &lt;atom&gt;)
  265. </code></pre>
  266. <p>Definition. Binds an atom to a symbol (globally).</p>
  267. <pre><code>(let &lt;symbol&gt; &lt;atom&gt;)
  268. </code></pre>
  269. <p>Definition. Binds an atom to a symbol (function-locally).</p>
  270. <pre><code>(fn &lt;arg1 argn …&gt; &lt;body&gt;)
  271. </code></pre>
  272. <p>Function. Defines a function with parameter symbols ("arguments") which can be used as placeholders anywhere in the function body.</p>
  273. <pre><code>(&lt;symbol&gt; &lt;arg1 argn…&gt;)
  274. </code></pre>
  275. <p>Application. Apply arguments to the function bound to the symbol.</p>
  276. <h2>Arithmetic</h2>
  277. <pre><code>(+), (-), (*), (/), (%)
  278. </code></pre>
  279. <p>Add, subtract, multiply, divide, modulus. These operate on integers. A non-nothing non-integer is interpreted as 1. Nothing is interpreted as 0. This allows logic to be constructed from arithmetic.</p>
  280. <pre><code>(gt &lt;a&gt; &lt;b&gt;), (lt &lt;a&gt; &lt;b&gt;), (eq &lt;a&gt; &lt;b&gt;)
  281. </code></pre>
  282. <p>Compare two values (a and b). Gt returns 1 if a is greater than b and 0 if not. Lt does the opposite. Eq returns 1 if a and b are equal (they represent the same number or object) and 0 if not.</p>
  283. <h2>Flow control</h2>
  284. <pre><code>(if &lt;condition&gt; &lt;then&gt; &lt;else&gt;)
  285. </code></pre>
  286. <p>Conditional branch. If condition evaluates to non-zero, <then> is evaluated, or else <else> is evaluted. The value of the evaluated branch is returned.</p>
  287. <pre><code>(while &lt;condition&gt; &lt;then&gt;)
  288. </code></pre>
  289. <p>Conditional loop. As long as condition evaluates to non-zero, <then> is evaluated over and over again. The value of the last evaluation is returned.</p>
  290. <pre><code>(do &lt;expr1&gt; &lt;exprn&gt; …)
  291. </code></pre>
  292. <p>Sequencing. Expressions are evaluated in the given order; The value of the last evaluation is returned.</p>
  293. <h2>Pairs &amp; Lists</h2>
  294. <pre><code>(cons &lt;a&gt; &lt;b&gt;)
  295. </code></pre>
  296. <p>Returns a pair of a and b: (a.b). </p>
  297. <pre><code>(car &lt;pair&gt;)
  298. </code></pre>
  299. <p>Returns the left side of a pair.</p>
  300. <pre><code>(cdr &lt;pair&gt;)
  301. </code></pre>
  302. <p>Returns the right side of a pair.</p>
  303. <pre><code>(quote &lt;s-expression&gt;)
  304. </code></pre>
  305. <p>Returns the given S-expression unmodified without evaluating it.</p>
  306. <pre><code>(list &lt;a&gt; &lt;b&gt; …)
  307. </code></pre>
  308. <p>Constructs a list from the given parameters.</p>
  309. <h2>Homoiconicity &amp; Reflection</h2>
  310. <pre><code>(read &lt;string&gt;)
  311. </code></pre>
  312. <p>Deserialization. Parses a string (text) into atoms.</p>
  313. <pre><code>(write &lt;op&gt;)
  314. </code></pre>
  315. <p>Serialization. Returns a string representation of the given atom.</p>
  316. <pre><code>(symbols)
  317. </code></pre>
  318. <p>Returns a list of all visible symbols.</p>
  319. <h2>Strings &amp; Buffers</h2>
  320. <p>Strings (text), byte strings (binary data) and files have a uniform interface in Interim OS. All system resources (see Section 3.6) in Interim OS are exposed as file systems which can be addressed using (open <path>). The opened "file" behaves exactly like a byte string; thus, a string created at run-time is a nameless file in memory.</p>
  321. <pre><code>(alloc 65536)
  322. </code></pre>
  323. <p>Returns a 64-kilobyte string of zeroes.</p>
  324. <pre><code>(size &lt;str&gt;)
  325. </code></pre>
  326. <p>Returns the length of a string in bytes.</p>
  327. <pre><code>(substr &lt;str&gt; &lt;offset&gt; &lt;length&gt;)
  328. </code></pre>
  329. <p>Returns a substring of length <length> that starts at <offset> bytes in the given string.</p>
  330. <pre><code>(put &lt;str&gt; &lt;offset&gt; &lt;byte&gt;)
  331. </code></pre>
  332. <p>Replaces the byte at position <offset> in the given string with a copy of <byte>.</p>
  333. <pre><code>(get &lt;str&gt; &lt;offset&gt;)
  334. </code></pre>
  335. <p>Returns the byte at position <offset> in the given string.</p>
  336. <h2>Filesystem</h2>
  337. <pre><code>(open "/path/to/file")
  338. </code></pre>
  339. <p>Returns a stream that is an interface to the file at the specified path.</p>
  340. <pre><code>(send &lt;sym&gt; &lt;str2&gt;)
  341. </code></pre>
  342. <p>Sends (appends) a string to the given symbol representing a stream.</p>
  343. <pre><code>(recv &lt;sym&gt; &lt;length&gt;)
  344. </code></pre>
  345. <p>Receives (consumes) up to <length> bytes from the stream represented by <sym>.</p>
  346. </body>
  347. </html>