<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arun Aditya on Medium]]></title>
        <description><![CDATA[Stories by Arun Aditya on Medium]]></description>
        <link>https://medium.com/@aruncse2k20?source=rss-61b50b5088a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lZmp50Vn0VOZaXiQ</url>
            <title>Stories by Arun Aditya on Medium</title>
            <link>https://medium.com/@aruncse2k20?source=rss-61b50b5088a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:55:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aruncse2k20/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Thought Android Used Bash. Then I Discovered mksh]]></title>
            <link>https://medium.com/@aruncse2k20/i-thought-android-used-bash-then-i-discovered-mksh-07086052b4b6?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/07086052b4b6</guid>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[linux-history]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 06:55:11 GMT</pubDate>
            <atom:updated>2026-08-09T06:55:11.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoAdwqJXT_U15dSapYMZeg.png" /></figure><p>When I started learning AOSP, I often used this command:</p><pre>adb shell</pre><p>It looked simple.</p><p>I connected my Android device, entered the shell, and started running commands:</p><pre>ls<br>ps<br>cd /data<br>getprop</pre><p>At first, I didn’t think much about what was actually happening.</p><p>I knew that Linux has a shell. I was familiar with Bash. Whenever I opened a terminal on Linux, I usually saw something like:</p><pre>$ echo $SHELL<br>/bin/bash</pre><p>So I naturally assumed Android was also using Bash.</p><p>I was wrong.</p><p>Android uses <strong>mksh — the MirBSD Korn Shell</strong>.</p><p>That small discovery led me to a much bigger question:</p><p><strong>What exactly is a shell, why are there so many different shells, and where does </strong><strong>mksh fit into all of this?</strong></p><p>So I went back to the beginning.</p><h3>What is a shell?</h3><p>Before talking about Bash ormksh, let&#39;s understand what a shell actually does.</p><p>A shell is simply a program that allows us to communicate with the operating system using commands.</p><p>For example, when I type:</p><pre>ls</pre><p>something needs to understand what ls means and execute it.</p><p>That is where the shell comes in.</p><p>A simplified picture looks like this:</p><pre>User<br>  |<br>  |  ls<br>  v<br>Shell<br>  |<br>  v<br>Operating System<br>  |<br>  v<br>Kernel</pre><p>The shell is therefore <strong>not the Linux kernel</strong>.</p><p>The shell sits between the user and the operating system and interprets commands.</p><p>It can also do much more than execute one command. It provides things like:</p><ul><li>Variables</li><li>Pipes</li><li>Redirection</li><li>Conditions</li><li>Loops</li><li>Functions</li><li>Shell scripts</li></ul><p>For example:</p><pre>NAME=&quot;Android&quot;</pre><pre>echo $NAME</pre><p>or:</p><pre>ps | grep system</pre><p>These are things the shell understands and manages.</p><p>Once I understood this, the next question became:</p><p><strong>Where did shells come from?</strong></p><h3>The story starts with Unix</h3><p>The history of modern shells is closely connected with Unix.</p><p>Around 1969, researchers at Bell Labs started developing Unix.</p><p>The early Unix systems already needed a way for users to interact with the operating system.</p><p>One of the early shells was the <strong>Thompson shell</strong>, developed by Ken Thompson.</p><p>It was relatively simple, but it introduced an extremely important idea:</p><p><strong>Pipelines.</strong></p><p>For example:</p><pre>ls | grep android</pre><p>The output of one command could become the input of another command.</p><p>That idea is still everywhere today.</p><p>But the Thompson shell was not designed to become a powerful programming language.</p><p>Something better was needed.</p><h3>Then came the Bourne Shell</h3><p>In the late 1970s, Stephen Bourne developed the <strong>Bourne shell</strong>.</p><p>It became commonly known as:</p><pre>sh</pre><p>This was a major step forward.</p><p>The shell could now be used for scripting.</p><p>We could write things like:</p><pre>if [ &quot;$USER&quot; = &quot;root&quot; ]; then<br>    echo &quot;I am root&quot;<br>else<br>    echo &quot;I am not root&quot;<br>fi</pre><p>We could use:</p><pre>for<br>while<br>if<br>case</pre><p>along with variables, functions, pipes, and redirection.</p><p>The shell was no longer just a command interpreter.</p><p>It had become a programming environment.</p><p>And this is where the story becomes interesting.</p><p>The Bourne shell became the foundation for many shells that came later.</p><h3>Not everyone wanted the same shell</h3><p>As Unix became more popular, different developers wanted different things from their shell.</p><p>One group wanted a shell with syntax that looked more like the C programming language.</p><p>That led to <strong>C shell (</strong><strong>csh)</strong>, associated with Bill Joy and the BSD Unix world.</p><p>Its syntax was different from Bourne shell syntax.</p><p>So we started to get different shell families:</p><pre>Unix Shells<br>     |<br>     +---- Bourne Shell family<br>     |<br>     +---- C Shell family</pre><p>The C shell eventually led to shells such as tcsh.</p><p>But the Bourne family continued to grow.</p><h3>The Korn Shell arrives</h3><p>At Bell Labs, David Korn developed another shell called <strong>KornShell</strong>, or simply:</p><pre>ksh</pre><p>KornShell was designed to keep compatibility with the Bourne shell while providing more powerful features for interactive use and scripting.</p><p>Now we had something like:</p><pre>Bourne Shell<br>      |<br>      v<br>    KornShell<br>      |<br>      v<br>     ksh</pre><p>And this is the part that eventually brings us to Android.</p><h3>Then came Bash</h3><p>If you have used Linux, you have probably heard of Bash.</p><p>Bash stands for:</p><p><strong>Bourne Again Shell</strong></p><p>The name itself is a joke based on the Bourne shell.</p><p>Bash was created for the GNU Project and became extremely popular on Linux systems.</p><p>It kept the familiar Bourne shell style while adding many useful features.</p><p>For example:</p><pre>name=&quot;Arun&quot;</pre><pre>echo &quot;$name&quot;</pre><p>Bash also provides powerful arrays, advanced parameter expansion, command history, completion, job control and many other features.</p><p>That is why Bash became such a common choice for Linux users.</p><p>On a typical Linux machine, you might see:</p><pre>$ echo $SHELL<br>/bin/bash</pre><p>At this point, I was thinking:</p><blockquote><em>“Okay, Bash is the standard shell on Linux. So Android must also use Bash, right?”</em></blockquote><p>Again, no.</p><h3>Android took a different path</h3><p>Android is built on the Linux kernel, but Android is not simply a normal Linux desktop distribution.</p><p>It is designed for phones, cars, TVs, watches and other embedded devices.</p><p>That means Android has different requirements.</p><p>It doesn’t necessarily need every feature that a large desktop shell provides.</p><p>Android therefore uses:</p><p><strong>mksh — MirBSD Korn Shell.</strong></p><p>And suddenly the name started making sense.</p><pre>KornShell<br>    |<br>    v<br>  mksh<br>    |<br>    v<br> Android</pre><p>mksh is part of the Korn shell family.</p><p>It provides the shell functionality Android needs while being suitable for a relatively constrained environment.</p><h3>So what exactly is mksh?</h3><p>mksh stands for:</p><p><strong>MirBSD Korn Shell</strong></p><p>It is a Unix shell derived from the Korn shell family.</p><p>Like Bash, it can:</p><ul><li>Execute commands</li><li>Run shell scripts</li><li>Create variables</li><li>Use pipes</li><li>Redirect input and output</li><li>Use conditions</li><li>Use loops</li><li>Define functions</li></ul><p>For example:</p><pre>NAME=&quot;Android&quot;</pre><pre>echo &quot;$NAME&quot;</pre><p>works as a normal shell operation.</p><p>You can also do:</p><pre>ps | grep system</pre><p>So when you first look atmksh, it can feel very similar to Bash.</p><p>And for many basic commands, it is.</p><p>But that doesn’t mean Bash and mksh are the same thing.</p><h3>Bash vs mksh</h3><p>This is where I started paying more attention.</p><p>Both shells come from the broader Unix shell world, but they have different histories and different feature sets.</p><p>BashmkshFull nameBourne Again Shell MirBSD Korn Shell Family Bourne shell familyKorn shell familyCommon environmentLinux desktops/serversAndroid and Unix-like systemsInteractive shellYesYesShell scriptingYesYesPOSIX-style scriptingYesYesAdvanced featuresVery extensiveMore focusedAndroid default shellNoYes</p><p>One important thing to understand is:</p><p><strong>mksh is not simply a smaller version of Bash.</strong></p><p>They are different shell implementations.</p><p>They share a lot of traditional shell syntax, but they also have differences.</p><h3>Why does this difference matter?</h3><p>Suppose I write a shell script on my Ubuntu machine.</p><p>I might use some Bash-specific feature without even realizing it.</p><p>For example:</p><pre>#!/bin/bash</pre><pre>numbers=(10 20 30)</pre><pre>echo &quot;${numbers[0]}&quot;</pre><p>This works because Bash has powerful array support.</p><p>But if I take the same script and expect it to work everywhere, I may run into problems.</p><p>This is especially important when working with Android.</p><p>If an Android script starts with:</p><pre>#!/system/bin/sh</pre><p>I should not assume that every Bash feature is available.</p><p>This is one of the reasons portable shell scripting matters in AOSP.</p><h3>What happens when I run adb shell?</h3><p>This was probably the most useful part of the whole thing for me.</p><p>When I type:</p><pre>adb shell</pre><p>I am not somehow opening a Bash terminal on my Android phone.</p><p>Conceptually, the flow looks more like this:</p><pre>My Computer<br>     |<br>     | adb shell<br>     v<br>Android Device<br>     |<br>     v<br>/system/bin/sh<br>     |<br>     v<br>mksh<br>     |<br>     v<br>Android commands<br>     |<br>     v<br>Linux kernel</pre><p>This is a much better mental model when working with AOSP.</p><h3>But where does toybox come into the picture?</h3><p>There was another thing that confused me.</p><p>If mksh is the shell, then where do commands such as:</p><pre>ls<br>ps<br>cat<br>grep</pre><p>come from?</p><p>The answer is that many common Android command-line utilities are provided by <strong>Toybox</strong>.</p><p>So we can simplify the Android command line into:</p><pre>Android<br>                    |<br>                    v<br>                  mksh<br>                    |<br>          +---------+---------+<br>          |                   |<br>     Shell built-ins       Commands<br>          |                   |<br>      cd, export,        ls, ps, cat...<br>      if, for...              |<br>                              v<br>                           Toybox</pre><p>This distinction is important.</p><p><strong>mksh is the shell.</strong></p><p><strong>Toybox provides many of the commands that we run from that shell.</strong></p><p>They are two different things.</p><h3>Shell vs Terminal</h3><p>There is another small confusion I had when learning this.</p><p>A <strong>terminal emulator</strong> is not the same thing as a shell.</p><p>For example, on a Linux desktop:</p><pre>Terminal Emulator<br>       |<br>       v<br>      Bash<br>       |<br>       v<br>Linux Kernel</pre><p>The terminal emulator gives me the window where I type.</p><p>Bash interprets what I type.</p><p>The kernel performs the underlying operating-system work.</p><p>Similarly, on Android:</p><pre>adb<br> |<br> v<br>Android<br> |<br> v<br>/system/bin/sh<br> |<br> v<br>mksh<br> |<br> v<br>Linux kernel</pre><p>Once you separate these concepts, the whole thing becomes much easier to understand.</p><h3>The shell family tree</h3><p>After going through this history, I found it useful to keep a simple family tree in my head.</p><pre>Unix<br>                     |<br>          +----------+----------+<br>          |                     |<br>          v                     v<br>    Thompson Shell           Other ideas<br>          |<br>          v<br>    Bourne Shell<br>          |<br>     +----+----------------+<br>     |                     |<br>     v                     v<br>   KornShell              Bash<br>     |<br>     v<br>   mksh<br>     |<br>     v<br>  Android</pre><p>And separately:</p><pre>C Shell<br>   |<br>   v<br> tcsh</pre><p>Later, other shells such as zsh and fish also became popular.</p><h3>What about zsh and fish?</h3><p>There are many shells today.</p><p>For example, <strong>zsh</strong> is known for powerful interactive features, completion and customization.</p><p>macOS now uses zsh as its default shell.</p><p>Then there is <strong>fish</strong>, which stands for Friendly Interactive Shell.</p><p>Fish focuses heavily on making the interactive terminal experience easier, with features such as syntax highlighting and autosuggestions.</p><p>But fish deliberately does not try to be POSIX shell compatible in the same way as traditional shells.</p><p>So different shells make different trade-offs.</p><h3>Why are there so many shells?</h3><p>This question actually has a simple answer.</p><p>Different people wanted different things.</p><p>Some wanted:</p><p><strong>Portability</strong></p><pre>sh<br>dash<br>ash</pre><p>Some wanted:</p><p><strong>Powerful scripting and compatibility</strong></p><pre>ksh<br>bash</pre><p>Some wanted:</p><p><strong>A better interactive experience</strong></p><pre>zsh<br>fish</pre><p>And some environments needed:</p><p><strong>A small shell suitable for embedded systems</strong></p><pre>ash<br>mksh</pre><p>There isn’t one shell that is perfect for every situation.</p><h3>What I finally understood</h3><p>Before learning about mksh, I thought of a shell simply as &quot;the black terminal where I type Linux commands.&quot;</p><p>Now I think about it differently.</p><p>A shell is a <strong>program and a scripting language that sits between the user and the operating system</strong>.</p><p>And there isn’t just one shell.</p><p>There is a long history behind the command line we use every day:</p><pre>Thompson Shell<br>      ↓<br>Bourne Shell<br>      ↓<br>KornShell<br>      ↓<br>mksh<br>      ↓<br>Android</pre><p>While another branch went toward:</p><pre>Bourne Shell<br>      ↓<br>Bash<br>      ↓<br>Linux desktops</pre><p>And other branches produced:</p><pre>csh → tcsh</pre><pre>zsh</pre><pre>fish</pre><h3>Why this matters for AOSP</h3><p>For someone learning AOSP, understanding the shell is more useful than it might initially seem.</p><p>When I run:</p><pre>adb shell</pre><p>I am entering an Android environment where several layers are working together.</p><p>A simplified view is:</p><pre>Android Device<br>                       |<br>                       v<br>                    /system<br>                       |<br>                       v<br>                /system/bin/sh<br>                       |<br>                       v<br>                     mksh<br>                       |<br>             +---------+---------+<br>             |                   |<br>       Shell built-ins        Toybox<br>             |                   |<br>             +---------+---------+<br>                       |<br>                       v<br>                Linux system calls<br>                       |<br>                       v<br>                    Kernel</pre><p>This connects several AOSP concepts that may initially feel unrelated.</p><p>init, system services, permissions, SELinux, processes, /system/bin, Toybox, mksh, system calls and the Linux kernel are all parts of the same larger system.</p><p>And that is probably the biggest lesson I got from this small question:</p><p><strong>Sometimes understanding one small command like </strong><strong>adb shell can lead you all the way down to the Linux kernel.</strong></p><p>That is what makes learning AOSP interesting.</p><h3>Final takeaway</h3><p>If you are just starting with Linux or AOSP, you don’t need to memorize every shell and its history.</p><p>Just remember these:</p><pre>sh     → traditional Unix/Bourne shell interface<br>bash   → Bourne Again Shell, very common on Linux<br>ksh    → KornShell<br>mksh   → MirBSD Korn Shell, used by Android<br>zsh    → powerful interactive shell<br>fish   → user-friendly interactive shell</pre><p>And most importantly:</p><blockquote><strong><em>Bash is not the Linux shell. </em></strong><strong><em>mksh is not the Android programming language. They are both shell programs that interpret commands and scripts.</em></strong></blockquote><p>Once that distinction is clear, the Android command line starts making a lot more sense.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07086052b4b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading and Writing Weren't Enough… So I Taught My Driver a New Language with ioctl()]]></title>
            <link>https://medium.com/@aruncse2k20/reading-and-writing-werent-enough-so-i-taught-my-driver-a-new-language-with-ioctl-b9215bba0a84?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9215bba0a84</guid>
            <category><![CDATA[linux-kernel-module]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[character-device-driver]]></category>
            <category><![CDATA[android-framework]]></category>
            <category><![CDATA[learn-linux-device-driver]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 18:40:37 GMT</pubDate>
            <atom:updated>2026-07-27T18:40:37.012Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3B-2B-1 of my Linux Device Driver Journey on Raspberry Pi 5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5W3M2C-W34Sce8EIV-foFw.png" /></figure><blockquote><em>&quot;Our driver could now read data and write data. It finally felt like a real Linux device. But then I discovered something that almost every professional Linux driver uses—</em><em>ioctl().&quot;</em></blockquote><p>By now, our character driver has come a long way.</p><p>A user can write data into our driver using</p><pre>echo &quot;hello world&quot; &gt; /dev/mybuf</pre><p>and read it back using</p><pre>cat /dev/mybuf</pre><p>The kernel calls our</p><ul><li>mybuf_write()</li><li>mybuf_read()</li></ul><p>functions automatically.</p><p>Everything works perfectly.</p><p>Or at least...</p><p>that&#39;s what I thought.</p><h3>The First Limitation</h3><p>Imagine we want our driver to support a new feature.</p><p>Suppose we want to <strong>erase the buffer</strong>.</p><p>How should we do it?</p><p>One idea might be</p><pre>echo &quot;RESET&quot; &gt; /dev/mybuf</pre><p>Inside write(), we could check</p><pre>if (strcmp(kbuffer, &quot;RESET&quot;) == 0)</pre><p>and clear the buffer.</p><p>Technically...</p><p>this works.</p><p>But it is a terrible design.</p><p>Why?</p><p>Because the word</p><pre>RESET</pre><p>is not really <strong>data</strong>.</p><p>It is a <strong>command</strong>.</p><p>Those are two completely different things.</p><h3>Data vs Commands</h3><p>Think about a printer.</p><p>Sometimes you send it</p><pre>A document</pre><p>Other times you send</p><pre>Print in color<br><br>Print double-sided<br><br>Cancel current job</pre><p>The document is data.</p><p>The remaining items are instructions.</p><p>Linux treats them differently.</p><p>The same idea applies to our driver.</p><p>Writing</p><pre>Hello World</pre><p>means</p><blockquote><em>Store this text.</em></blockquote><p>Writing</p><pre>RESET</pre><p>means</p><blockquote><em>Perform an action.</em></blockquote><p>Trying to mix both together quickly becomes confusing.</p><p>Linux needed a better solution.</p><h3>Enter ioctl()</h3><p>To solve this problem,</p><p>Unix introduced a special system call decades ago.</p><p>Its name is</p><pre>ioctl</pre><p>which stands for</p><blockquote><strong><em>Input / Output Control</em></strong></blockquote><p>Unlike</p><pre>read()</pre><p>and</p><pre>write()</pre><p>ioctl() is not designed to transfer ordinary data.</p><p>Instead,</p><p>it sends</p><ul><li>commands</li><li>configuration requests</li><li>control messages</li></ul><p>to a device driver.</p><p>Think of it as giving instructions instead of sending information.</p><h3>A Simple Analogy</h3><p>Imagine your television.</p><p>Pressing</p><pre>Volume +</pre><p>doesn&#39;t send a movie to the TV.</p><p>It sends a command.</p><p>Likewise,</p><p>pressing</p><pre>Power Off</pre><p>doesn&#39;t transfer data.</p><p>It tells the television to perform an action.</p><p>That&#39;s exactly what ioctl() does.</p><p>Instead of saying</p><blockquote><em>&quot;Here is some data.&quot;</em></blockquote><p>it says</p><blockquote><em>&quot;Please do something.&quot;</em></blockquote><h3>Why Professional Drivers Use ioctl()</h3><p>Almost every Linux driver uses ioctl().</p><p>For example,</p><p>a camera driver may support commands like</p><pre>Focus<br><br>Zoom<br><br>Capture Image<br><br>Enable Flash</pre><p>A network driver may support</p><pre>Enable Promiscuous Mode<br><br>Reset Adapter<br><br>Get Statistics</pre><p>A graphics driver might receive</p><pre>Allocate GPU Memory<br><br>Change Display Mode<br><br>Enable VSync</pre><p>None of these are ordinary data.</p><p>They are requests asking the driver to perform specific actions.</p><h3>Our Driver Needs a Command Too</h3><p>Our driver stores text inside</p><pre>kbuffer[]</pre><p>Sometimes,</p><p>we may want to erase everything.</p><p>Instead of writing</p><pre>RESET</pre><p>into the buffer,</p><p>we&#39;ll teach the driver a proper command.</p><p>We&#39;ll call it</p><pre>MYBUF_RESET</pre><p>Now,</p><p>instead of sending text,</p><p>applications will send a command identifier.</p><p>When the driver receives that command,</p><p>it clears the buffer.</p><p>Simple.</p><p>Clean.</p><p>Professional.</p><h3>Every Command Needs an Identity</h3><p>Imagine a restaurant.</p><p>Customers don&#39;t tell the kitchen</p><blockquote><em>&quot;Bring me the third item on page two.&quot;</em></blockquote><p>Instead,</p><p>every dish has a unique number.</p><p>For example</p><pre>101 → Veg Burger<br><br>102 → Pizza<br><br>103 → Pasta</pre><p>The waiter simply sends</p><pre>102</pre><p>and everyone understands</p><p>that means</p><pre>Pizza</pre><p>Linux drivers work the same way.</p><p>Each ioctl() command has its own unique number.</p><h3>Creating Command Numbers</h3><p>Inside our driver,</p><p>we define</p><pre>#define MYBUF_IOC_MAGIC &#39;M&#39;</pre><p>and</p><pre>#define MYBUF_RESET _IO(MYBUF_IOC_MAGIC, 0)</pre><p>At first,</p><p>this looks mysterious.</p><p>Let&#39;s break it apart.</p><h3>What Is the Magic Number?</h3><p>The first definition is</p><pre>&#39;M&#39;</pre><p>This is called the</p><p><strong>Magic Number</strong>.</p><p>Its purpose is very simple.</p><p>Imagine hundreds of drivers running inside Linux.</p><p>If every driver used</p><pre>Command 0</pre><p>Linux would have no idea</p><p>which driver the command belongs to.</p><p>Instead,</p><p>each driver chooses its own identifier.</p><p>Our driver uses</p><pre>&#39;M&#39;</pre><p>because</p><pre>M<br><br>↓<br><br>MyBuf</pre><p>Another driver might choose</p><pre>&#39;S&#39;</pre><p>or</p><pre>&#39;C&#39;</pre><p>The exact character doesn&#39;t matter.</p><p>It simply needs to be unique enough for that driver.</p><p>Think of it as your driver&#39;s surname.</p><h3>What Does _IO() Mean?</h3><p>Now let&#39;s look at</p><pre>_IO(MYBUF_IOC_MAGIC, 0)</pre><p>This is not a function.</p><p>It is a kernel macro.</p><p>Its job is to generate a unique command number.</p><p>The macro combines</p><ul><li>the magic number</li><li>the command number</li></ul><p>into one integer.</p><p>Conceptually,</p><p>it works like this.</p><pre>Magic<br><br>&#39;M&#39;<br><br>+<br><br>Command<br><br>0<br><br>↓<br><br>Unique ioctl Command</pre><p>We don&#39;t have to calculate anything ourselves.</p><p>Linux does it for us.</p><h3>Why Not Just Write 0?</h3><p>Some beginners wonder</p><p>why we don’t simply write</p><pre>#define MYBUF_RESET 0</pre><p>Imagine another driver also uses</p><pre>0</pre><p>Now both drivers would have identical commands.</p><p>That would be a disaster.</p><p>Using _IO()</p><p>guarantees that command numbers remain unique.</p><p>That’s why every Linux driver follows this pattern.</p><h3>More Than One Command</h3><p>Suppose our driver grows in the future.</p><p>We might define</p><pre>Command 0</pre><pre>↓</pre><pre>Reset Buffer</pre><p>Later,</p><p>we could add</p><pre>Command 1</pre><pre>↓</pre><pre>Enable Debug</pre><p>and</p><pre>Command 2</pre><pre>↓</pre><pre>Return Driver Version</pre><p>Each one would become its own unique ioctl() command.</p><p>That’s why Linux uses command numbers instead of strings.</p><p>Numbers are</p><ul><li>faster,</li><li>smaller,</li><li>easier for the kernel to process.</li></ul><h3>How Does Linux Reach Our Driver?</h3><p>Earlier in this series,</p><p>we learned about</p><pre>struct file_operations</pre><p>We connected</p><pre>.unlocked_ioctl = mybuf_ioctl,</pre><p>inside that structure.</p><p>That means whenever a user program executes</p><pre>ioctl(...)</pre><p>Linux automatically calls</p><pre>mybuf_ioctl()</pre><p>inside our driver.</p><p>The flow looks like this.</p><pre>User Application</pre><pre>        │</pre><pre>        ▼</pre><pre>ioctl()</pre><pre>        │</pre><pre>        ▼</pre><pre>Linux Kernel</pre><pre>        │</pre><pre>Looks inside</pre><pre>file_operations</pre><pre>        │</pre><pre>        ▼</pre><pre>mybuf_ioctl()</pre><pre>        │</pre><pre>        ▼</pre><pre>Driver Executes Command</pre><p>Just like read() and write(),</p><p>applications never call our driver directly.</p><p>Linux acts as the bridge.</p><h3>Looking Ahead</h3><p>We’ve now answered three important questions.</p><p>✔ Why read() isn&#39;t enough.</p><p>✔ Why write() isn&#39;t enough.</p><p>✔ Why Linux introduced ioctl().</p><p>We’ve also learned how Linux creates unique command IDs using</p><ul><li>MYBUF_IOC_MAGIC</li><li>_IO()</li><li>MYBUF_RESET</li></ul><p>But one mystery still remains.</p><p>What actually happens <strong>inside</strong> mybuf_ioctl()?</p><p>How does our driver recognize the command?</p><p>How does it clear the buffer?</p><p>And what happens if an application sends a command the driver doesn’t understand?</p><p>In the next article, we’ll step insidemybuf_ioctl(), explain every line of code, learn about switch(cmd), memset(), ENOTTY, and finally implement our very first custom command in the Linux kernel.</p><p>By the end of that article, you’ll understand how real Linux drivers expose powerful features beyond simple reads and writes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9215bba0a84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Created /dev/mybuf... But How Did Linux Know Which Function to Call?]]></title>
            <link>https://medium.com/@aruncse2k20/i-created-dev-mybuf-but-how-did-linux-know-which-function-to-call-c6663e55501f?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6663e55501f</guid>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[learn-linux-device-driver]]></category>
            <category><![CDATA[android-framework]]></category>
            <category><![CDATA[android-bsp]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 17:40:33 GMT</pubDate>
            <atom:updated>2026-07-25T17:40:33.429Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3B-1 of my Linux Device Driver Journey on Raspberry Pi 5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77n_V9wJ1_211tBnvJnpew.png" /></figure><blockquote><em>“Creating a device file was exciting. But the real magic happens when someone opens that file. How does Linux know which function inside our driver should run?”</em></blockquote><p>At the end of the previous article, something amazing happened.</p><p>Our driver registered itself with the Linux kernel.</p><p>Linux even created a new device for us.</p><pre>/dev/mybuf</pre><p>For the first time in this series, we had something that looked like a real Linux device.</p><p>But then I started wondering.</p><p>Suppose someone types</p><pre>cat /dev/mybuf</pre><p>How does Linux know that it should call <strong>my</strong> code?</p><p>Or what happens when someone writes</p><pre>echo &quot;hello&quot; &gt; /dev/mybuf</pre><p>Somewhere inside the kernel, Linux must decide</p><blockquote><em>“This device belongs to Arun’s driver.”</em></blockquote><p>Then it must call exactly the right function.</p><p>But how?</p><p>That’s exactly what we’ll learn in this article.</p><h3>Every Device Driver Needs a Reception Desk</h3><p>Imagine walking into a large hospital.</p><p>You don’t immediately meet the doctor.</p><p>First, you visit the reception desk.</p><p>The receptionist asks,</p><blockquote><em>“Why are you here?”</em></blockquote><p>Depending on your answer, they send you to the right department.</p><p>Linux works in almost the same way.</p><p>Whenever a program interacts with a device,</p><p>Linux first checks a table that tells it</p><ul><li>what to do when someone opens the device,</li><li>what to do when someone reads from it,</li><li>what to do when someone writes to it,</li><li>what to do when someone closes it.</li></ul><p>That table is called</p><pre>struct file_operations</pre><p>It is one of the most important structures in the Linux kernel.</p><h3>Meet struct file_operations</h3><p>Inside our driver we wrote</p><pre>static const struct file_operations mybuf_fops = {<br>    .owner          = THIS_MODULE,<br>    .open           = mybuf_open,<br>    .release        = mybuf_release,<br>    .read           = mybuf_read,<br>    .write          = mybuf_write,<br>    .unlocked_ioctl = mybuf_ioctl,<br>};</pre><p>At first glance, this looks like a simple structure.</p><p>But it completely changes how Linux communicates with our driver.</p><p>Think of it as a menu.</p><pre>                Linux Kernel<br>                    |</pre><pre>        Someone opens /dev/mybuf</pre><pre>                     │</pre><pre>                     ▼</pre><pre>          struct file_operations</pre><pre>      open()     read()     write()</pre><pre>      close()               ioctl()</pre><pre>                     │</pre><pre>                     ▼</pre><pre>            Functions in our driver</pre><p>Instead of guessing what to do,</p><p>Linux simply looks inside this structure.</p><h3>The Owner Field</h3><p>The first member is</p><pre>.owner = THIS_MODULE</pre><p>This tells Linux,</p><blockquote><em>“These functions belong to this kernel module.”</em></blockquote><p>Why is that important?</p><p>Imagine a program opens our driver.</p><p>While it is still using the driver,</p><p>someone executes</p><pre>sudo rmmod mybuf</pre><p>If Linux removed the module immediately,</p><p>the application would suddenly be executing code that no longer exists.</p><p>That would almost certainly crash the kernel.</p><p>Instead,</p><p>THIS_MODULE</p><p>tells Linux to keep our module alive while somebody is still using it.</p><p>It’s a simple line,</p><p>but it protects the kernel from a very dangerous situation.</p><h3>What Happens When Someone Opens the Device?</h3><p>Next,</p><pre>.open = mybuf_open</pre><p>Whenever a program opens</p><pre>/dev/mybuf</pre><p>Linux immediately calls</p><pre>mybuf_open()</pre><p>Our implementation is very small.</p><pre>static int mybuf_open(struct inode *inode,<br>                      struct file *file)<br>{<br>    printk(KERN_INFO &quot;mybuf: opened\n&quot;);<br>    return 0;<br>}</pre><p>For now,</p><p>we simply print a message.</p><p>Later,</p><p>real drivers may</p><ul><li>initialize hardware,</li><li>allocate memory,</li><li>enable interrupts,</li><li>verify permissions,</li><li>or prepare communication.</li></ul><p>Our driver keeps things simple.</p><h3>What Are These Two Parameters?</h3><p>The function receives</p><pre>struct inode *inode</pre><p>and</p><pre>struct file *file</pre><p>Don’t worry about their internals yet.</p><p>Just remember their roles.</p><p>The <strong>inode</strong> describes the device itself.</p><p>The <strong>file</strong> represents this particular open instance.</p><p>Imagine two terminal windows.</p><p>Both execute</p><pre>cat /dev/mybuf</pre><p>Each terminal gets its own</p><pre>struct file</pre><p>because each one represents a different open session.</p><p>The device stays the same.</p><p>The users are different.</p><h3>Returning Zero</h3><p>Our function ends with</p><pre>return 0;</pre><p>This tells Linux</p><blockquote><em>“Everything went well.”</em></blockquote><p>If something had gone wrong,</p><p>we could return an error instead.</p><p>For example,</p><pre>return -EBUSY;</pre><p>might tell Linux</p><p>that the device is already in use.</p><p>Returning negative error codes is very common in kernel programming.</p><h3>Closing the Device</h3><p>Eventually,</p><p>every open operation must end.</p><p>That’s where</p><pre>.release = mybuf_release</pre><p>comes in.</p><p>When the last user closes the device,</p><p>Linux calls</p><pre>mybuf_release()</pre><p>Our implementation is</p><pre>static int mybuf_release(struct inode *inode,<br>                         struct file *file)<br>{<br>    printk(KERN_INFO &quot;mybuf: closed\n&quot;);<br>    return 0;<br>}</pre><p>Again,</p><p>we simply log a message.</p><p>Real drivers often</p><ul><li>stop hardware,</li><li>free resources,</li><li>disable interrupts,</li><li>or save state.</li></ul><h3>Reading From the Device</h3><p>Now we reach one of the most important callbacks.</p><pre>.read = mybuf_read</pre><p>Whenever somebody executes</p><pre>cat /dev/mybuf</pre><p>Linux calls</p><pre>mybuf_read()</pre><p>Notice something interesting.</p><p>The user never calls this function directly.</p><p>They only execute</p><pre>cat</pre><p>Linux does the rest.</p><pre>User</pre><pre>cat /dev/mybuf</pre><pre>        │</pre><pre>        ▼</pre><pre>Linux Kernel</pre><pre>        │</pre><pre>        ▼</pre><pre>mybuf_read()</pre><pre>        │</pre><pre>        ▼</pre><pre>Return bytes</pre><pre>        │</pre><pre>        ▼</pre><pre>cat prints them</pre><p>That invisible journey is what makes Linux device drivers so elegant.</p><h3>Understanding the Read Function</h3><p>Our read callback begins like this.</p><pre>static ssize_t mybuf_read(<br>        struct file *file,<br>        char __user *buf,<br>        size_t len,<br>        loff_t *offset)</pre><p>There are four parameters.</p><p>Let’s understand them one by one.</p><h3>file</h3><p>This represents the currently opened device.</p><p>Linux passes it automatically.</p><h3>buf</h3><p>This is the user’s buffer.</p><p>The data we read must eventually be copied here.</p><p>Remember,</p><p>this memory belongs to user space.</p><p>We cannot write to it directly.</p><h3>len</h3><p>This tells us</p><p>how many bytes the application requested.</p><p>Suppose the application asks for</p><pre>100 bytes</pre><p>but our buffer contains only</p><pre>11 bytes</pre><p>We should return only those eleven bytes.</p><p>Not more.</p><h3>offset</h3><p>This one confuses many beginners.</p><p>Imagine a normal text file.</p><pre>Hello World</pre><p>After reading it once,</p><p>the file position reaches the end.</p><p>Reading again immediately returns</p><pre>EOF</pre><p>Linux expects device drivers to behave in a similar way.</p><p>That’s why our driver checks</p><pre>if (*offset &gt; 0)<br>    return 0;</pre><p>Returning</p><pre>0</pre><p>means</p><blockquote><em>“There is nothing more to read.”</em></blockquote><p>Without this check,</p><p>commands like</p><pre>cat /dev/mybuf</pre><p>would never stop.</p><h3>How Many Bytes Should We Copy?</h3><p>Next,</p><p>our driver calculates</p><pre>bytes_to_copy =<br>    (len &lt; data_len) ? len : data_len;</pre><p>This simply chooses</p><p>the smaller value.</p><p>Imagine</p><pre>User requested 100 bytes</pre><pre>Driver has 11 bytes</pre><p>The driver copies only</p><pre>11 bytes</pre><p>Now imagine</p><pre>User requested 5 bytes</pre><pre>Driver has 11 bytes</pre><p>The driver copies</p><pre>5 bytes</pre><p>This prevents reading beyond the available data.</p><h3>Crossing the Boundary Between Worlds</h3><p>Finally,</p><p>we reach</p><pre>copy_to_user()</pre><p>This is one of the most frequently used APIs in Linux drivers.</p><p>Remember,</p><p>our buffer lives inside the kernel.</p><p>The application lives in user space.</p><p>These two memory regions are isolated.</p><pre>+----------------------+<br>|      User Space      |<br>|                      |<br>|        cat           |<br>+----------------------+<br><br>          ▲<br>   copy_to_user()<br>          ▼<br>+----------------------+<br>|     Kernel Space     |<br>|                      |<br>|      kbuffer[]       |<br>+----------------------+</pre><p>Instead of exposing kernel memory directly,</p><p>Linux safely copies the requested bytes into the user’s buffer.</p><p>That’s exactly what</p><pre>copy_to_user()</pre><p>does.</p><h3>Updating the Offset</h3><p>After copying,</p><p>our driver executes</p><pre>*offset += bytes_to_copy;</pre><p>Now Linux knows</p><p>how much of the file has already been read.</p><p>The next read request reaches</p><pre>EOF</pre><p>instead of returning the same data forever.</p><p>It is a tiny line of code,</p><p>but without it,</p><p>our driver would behave incorrectly.</p><h3>Looking Ahead</h3><p>So far,</p><p>we’ve learned how Linux enters our driver.</p><p>We now understand</p><ul><li>struct file_operations</li><li>THIS_MODULE</li><li>open()</li><li>release()</li><li>read()</li><li>copy_to_user()</li><li>file offsets</li><li>EOF handling</li></ul><p>But one big question remains.</p><p>Reading data is useful.</p><p>How does data travel in the opposite direction?</p><p>How does</p><pre>echo &quot;hello world&quot; &gt; /dev/mybuf</pre><p>end up inside our kernel buffer?</p><p>In the next article,</p><p>we’ll follow that journey through write(), copy_from_user(), and finally explore how ioctl() lets us send custom commands to our driver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6663e55501f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Could Read From My Driver… But How Does Linux Send Data Back?]]></title>
            <link>https://medium.com/@aruncse2k20/i-could-read-from-my-driver-but-how-does-linux-send-data-back-7ede3dec6292?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ede3dec6292</guid>
            <category><![CDATA[learn-linux-device-driver]]></category>
            <category><![CDATA[linux-kernel-module]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[linux-device-drivers]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 17:20:01 GMT</pubDate>
            <atom:updated>2026-07-25T17:20:01.939Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3B-2A of my Linux Device Driver Journey on Raspberry Pi 5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzzFww8z83erW0K6-XZXDw.png" /></figure><blockquote><em>“In the previous article, we learned how Linux calls our </em><em>read() function when someone executes </em><em>cat /dev/mybuf. But a real device driver isn&#39;t just about sending data to user space—it also needs to receive data from it.&quot;</em></blockquote><p>At the end of the previous article, we answered one of the biggest questions in Linux device driver development.</p><p>When someone runs</p><pre>cat /dev/mybuf</pre><p>Linux eventually calls</p><pre>mybuf_read()</pre><p>inside our driver.</p><p>That felt almost magical.</p><p>A simple command typed in a terminal ended up executing our C code inside the Linux kernel.</p><p>But then another question came to my mind.</p><p>If Linux can <strong>read</strong> from our driver…</p><p>How does it <strong>write</strong> to it?</p><p>What really happens when someone types</p><pre>echo &quot;hello world&quot; &gt; /dev/mybuf</pre><p>Where does the text go?</p><p>Does Linux magically know where to store it?</p><p>Does it automatically copy it into our kernel buffer?</p><p>Or do we have to do that ourselves?</p><p>Let’s find out.</p><h3>Following the Journey of a Write Request</h3><p>Imagine typing</p><pre>echo &quot;hello world&quot; &gt; /dev/mybuf</pre><p>From the terminal, this looks like a very ordinary command.</p><p>But behind the scenes, Linux performs several steps.</p><pre>User Space<br>echo &quot;hello world&quot;<br>        │<br>        ▼<br>Virtual File System (VFS)<br>        │<br>Finds /dev/mybuf<br>        │<br>Looks inside file_operations<br>        │<br>Calls<br>mybuf_write()<br>        │<br>Driver stores data<br>inside kernel buffer</pre><p>The important thing to remember is this:</p><p>The shell never calls mybuf_write() directly.</p><p>Instead, Linux acts as the middleman.</p><h3>Our Write Callback</h3><p>Inside our driver, we connected</p><pre>.write = mybuf_write,</pre><p>inside</p><pre>struct file_operations</pre><p>That means every write request eventually reaches this function.</p><pre>static ssize_t mybuf_write(struct file *file,<br>                           const char __user *buf,<br>                           size_t len,<br>                           loff_t *offset)</pre><p>If this function looks familiar, that’s because it is very similar to mybuf_read().</p><p>Only the direction of the data has changed.</p><p>Instead of</p><pre>Kernel<br>↓<br>User</pre><p>we now have</p><pre>User<br>↓<br>Kernel</pre><h3>Understanding the Parameters</h3><p>Let’s understand each parameter.</p><h3>file</h3><pre>struct file *file</pre><p>Just like before,</p><p>this represents the currently opened device.</p><p>Linux creates and manages this structure automatically.</p><p>Our driver rarely needs to touch it in simple examples.</p><h3>buf</h3><pre>const char __user *buf</pre><p>This is the most important parameter.</p><p>Notice something interesting.</p><pre>__user</pre><p>appears again.</p><p>This tells us</p><blockquote><em>“This pointer belongs to user space.”</em></blockquote><p>In other words,</p><p>the string</p><pre>hello world</pre><p>is <strong>not</strong> inside the kernel.</p><p>It still belongs to the application that executed</p><pre>echo &quot;hello world&quot;</pre><p>If we want to keep it,</p><p>we must copy it into kernel memory ourselves.</p><h3>len</h3><pre>size_t len</pre><p>This tells us</p><p>how many bytes the application wants to write.</p><p>Suppose the user executes</p><pre>echo &quot;hello world&quot; &gt; /dev/mybuf</pre><p>The kernel tells our driver</p><pre>len = 11</pre><p>because</p><pre>hello world</pre><p>contains eleven characters.</p><p>The driver doesn’t have to count them.</p><p>Linux already did that for us.</p><h3>offset</h3><p>The final parameter is</p><pre>loff_t *offset</pre><p>For this simple driver,</p><p>we don’t really use it.</p><p>Later,</p><p>when we build more advanced drivers,</p><p>the file position becomes much more important.</p><p>For now,</p><p>we can safely ignore it.</p><h3>Our Driver Has Limited Memory</h3><p>At the beginning of our driver,</p><p>we declared</p><pre>#define BUF_SIZE 32</pre><p>and</p><pre>static char kbuffer[BUF_SIZE];</pre><p>That means our kernel buffer looks something like this.</p><pre>+--------------------------------+<br>|                                |<br>|         32 Bytes               |<br>|                                |<br>+--------------------------------+</pre><p>This is all the storage our driver owns.</p><p>Nothing more.</p><p>Nothing less.</p><h3>What If Someone Writes Too Much?</h3><p>Imagine someone executes</p><pre>echo &quot;This is a very long sentence...&quot; &gt; /dev/mybuf</pre><p>What if the string is</p><p>100 bytes long?</p><p>Our driver can only store</p><p>32 bytes.</p><p>Should we continue writing anyway?</p><p>Absolutely not.</p><p>Writing beyond the end of an array is one of the fastest ways to crash a kernel.</p><p>Instead,</p><p>our driver protects itself.</p><pre>if (len &gt; BUF_SIZE)<br>    len = BUF_SIZE;</pre><p>This tiny piece of code prevents buffer overflow.</p><p>If the user sends</p><pre>100 bytes</pre><p>our driver simply accepts</p><pre>32 bytes</pre><p>and ignores the rest.</p><p>Safety always comes first in kernel programming.</p><h3>Crossing the Boundary Again</h3><p>Earlier,</p><p>when we discussed read(),</p><p>we learned about</p><pre>copy_to_user()</pre><p>Now we’re going in the opposite direction.</p><pre>copy_from_user(kbuffer, buf, len)</pre><p>Notice the name.</p><pre>copy</pre><pre>FROM</pre><pre>user</pre><p>The direction is now reversed.</p><pre>+----------------------+<br>|      User Space      |<br>|                      |<br>|  &quot;hello world&quot;       |<br>+----------------------+<br><br>          │<br> copy_from_user()<br>          ▼<br>+----------------------+<br>|     Kernel Space     |<br>|                      |<br>|     kbuffer[]        |<br>+----------------------+</pre><p>The data moves safely into kernel memory.</p><p>This is the only correct way to access user-space data.</p><p>Never try to read the user pointer directly.</p><p>Always use</p><pre>copy_from_user()</pre><h3>What If the Copy Fails?</h3><p>Our driver checks</p><pre>if (copy_from_user(kbuffer, buf, len))<br>    return -EFAULT;</pre><p>This is another common kernel pattern.</p><p>Sometimes,</p><p>the user pointer might be invalid.</p><p>Perhaps it points to memory that no longer exists.</p><p>Perhaps the application passed an incorrect address.</p><p>Instead of crashing,</p><p>the kernel simply returns</p><pre>-EFAULT</pre><p>which stands for</p><blockquote><strong><em>Bad memory address</em></strong></blockquote><p>Linux handles the error gracefully,</p><p>and the application receives a failure instead of bringing down the entire operating system.</p><h3>Remembering How Much Data We Stored</h3><p>Once the copy succeeds,</p><p>our driver executes</p><pre>data_len = len;</pre><p>Why do we need another variable?</p><p>Because our buffer always contains</p><p>32 bytes.</p><p>But only part of it may actually contain useful data.</p><p>Imagine we wrote</p><pre>hello</pre><p>The memory now looks like this.</p><pre>+--------------------------------+<br>| h | e | l | l | o | ? | ? | ? |<br>+--------------------------------+</pre><pre>data_len = 5</pre><p>The remaining bytes are meaningless.</p><p>Later,</p><p>when someone calls</p><pre>cat /dev/mybuf</pre><p>our read() function uses</p><pre>data_len</pre><p>to know exactly how many bytes should be returned.</p><p>Without this variable,</p><p>the driver wouldn’t know where the real data ends.</p><h3>Returning the Number of Bytes Written</h3><p>Finally,</p><p>our function ends with</p><pre>return len;</pre><p>This tells Linux</p><blockquote><em>“I successfully stored this many bytes.”</em></blockquote><p>The shell interprets this as a successful write operation.</p><p>Everything worked exactly as expected.</p><h3>Following the Complete Journey</h3><p>Let’s put everything together.</p><p>When we execute</p><pre>echo &quot;hello world&quot; &gt; /dev/mybuf</pre><p>this is what really happens.</p><pre>     echo<br>      │<br>      ▼<br>Virtual File System<br>      │<br>      ▼<br>file_operations<br>      │<br>      ▼<br>mybuf_write()<br>      │<br>      ▼<br>copy_from_user()<br>      │<br>      ▼<br>kbuffer[]<br>      │<br>      ▼<br>data_len = 11<br>      │<br>      ▼<br>return 11</pre><p>Every write request follows this exact path.</p><p>The application never touches kernel memory directly.</p><p>Linux carefully transfers the data through our driver.</p><h3>Reading It Back</h3><p>Now something interesting happens.</p><p>Suppose we execute</p><pre>echo &quot;hello world&quot; &gt; /dev/mybuf</pre><p>Immediately afterwards,</p><p>we run</p><pre>cat /dev/mybuf</pre><p>What happens?</p><p>Our read() callback returns exactly what our write() callback stored.</p><pre>hello world</pre><p>The kernel buffer acts like a tiny notebook.</p><p>One function writes into it.</p><p>Another function reads from it.</p><p>Together,</p><p>they form a very simple character device driver.</p><h3>Looking Ahead</h3><p>At this point,</p><p>our driver can finally communicate in both directions.</p><p>It can</p><ul><li>receive data from user space,</li><li>store it safely inside kernel memory,</li><li>and send it back whenever someone reads the device.</li></ul><p>That’s already enough to build many simple character drivers.</p><p>But there is still one feature left.</p><p>Sometimes,</p><p>reading and writing data isn’t enough.</p><p>What if we want to send commands like</p><ul><li>reset the device,</li><li>erase the buffer,</li><li>enable a feature,</li><li>change a mode,</li><li>configure hardware?</li></ul><p>Those aren’t really “data.”</p><p>They’re instructions.</p><p>Linux solves this problem with one of the oldest and most powerful system calls:</p><pre>ioctl()</pre><p>In the next article, we’ll teach our driver its first custom command and discover how professional Linux drivers communicate with user applications beyond simple reads and writes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ede3dec6292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Kernel Module Was Finally Ready to Become a Device Driver]]></title>
            <link>https://medium.com/@aruncse2k20/my-kernel-module-was-finally-ready-to-become-a-device-driver-1e15ea434857?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e15ea434857</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[linux-device-drivers]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[linux-driver-tutorial]]></category>
            <category><![CDATA[learn-linux-device-driver]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 20:41:08 GMT</pubDate>
            <atom:updated>2026-07-23T20:41:08.083Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3A of my Linux Device Driver Journey on Raspberry Pi 5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ks-B_KCgXxVTucaqnkLgw.png" /></figure><blockquote><em>“For the first two articles, our kernel module could print messages, accept parameters, and even create files inside </em><em>/proc. But there was one thing it still couldn&#39;t do—it couldn&#39;t behave like a real Linux device.&quot;</em></blockquote><p>If you’ve been following this series, you’ve probably noticed something.</p><p>Our kernel modules have become smarter with every article.</p><p>In Part 1, they simply printed messages using printk().</p><p>In Part 2, they accepted module parameters and created their own file inside the /proc filesystem.</p><p>That was exciting.</p><p>But there was still something missing.</p><p>Whenever we wanted to communicate with our module, we had to use special kernel interfaces like /proc.</p><p>Real Linux device drivers don’t usually work that way.</p><p>Instead, they expose a <strong>device file</strong> inside the /dev directory.</p><p>That’s how applications communicate with keyboards.</p><p>That’s how they communicate with serial ports.</p><p>That’s how they communicate with cameras.</p><p>That’s how they communicate with sensors.</p><p>And that’s exactly what we’re going to build today.</p><p>For the first time in this series, our kernel module is going to become a <strong>character device driver</strong>.</p><h3>A Different Way to Talk to the Kernel</h3><p>Imagine writing a normal text file.</p><pre>echo &quot;Hello&quot; &gt; notes.txt</pre><p>Or reading it.</p><pre>cat notes.txt</pre><p>Simple.</p><p>Now imagine doing exactly the same thing…</p><p>…except the file isn’t stored on your SD card.</p><p>Instead, every read and write operation is handled by your own code running inside the Linux kernel.</p><p>That’s the idea behind a character device.</p><p>To a user, it looks like an ordinary file.</p><p>To the kernel, every operation is actually a function call inside your driver.</p><p>That is one of the most beautiful ideas in Linux.</p><p><strong>Everything looks like a file.</strong></p><h3>Meet the /dev Directory</h3><p>If you’ve ever explored Linux, you’ve probably seen something like this.</p><pre>/dev/null<br>/dev/tty<br>/dev/random<br>/dev/zero</pre><p>These aren’t ordinary files.</p><p>Most of them don’t contain data stored on disk.</p><p>Instead, they represent devices.</p><p>When an application opens one of these files, Linux forwards the request to a device driver.</p><p>Our goal is to create another one.</p><pre>/dev/mybuf</pre><p>This file doesn’t exist yet.</p><p>By the end of this article, Linux will create it automatically.</p><h3>What Is a Character Device?</h3><p>Linux supports several kinds of devices.</p><p>The two most common are:</p><p>Type ========================Example</p><p>Character <br>Device ==============Keyboard, serial port, USB UART, virtual drivers</p><p>Block Device =================Hard disk, SSD, SD card</p><p>A <strong>character device</strong> transfers data one stream at a time.</p><p>Think of typing on a keyboard.</p><p>Every key press arrives one after another.</p><p>A <strong>block device</strong>, on the other hand, works with fixed-size blocks of data.</p><p>For example, when Linux reads a file from your SD card, it doesn’t read one character at a time.</p><p>It reads blocks.</p><p>Our driver is much simpler.</p><p>So we’ll start with a character device.</p><h3>What Will Our Driver Do?</h3><p>Instead of controlling real hardware, we’ll build a tiny memory buffer inside the kernel.</p><p>It behaves like this.</p><pre>User Space</pre><pre>echo &quot;hello&quot; &gt; /dev/mybuf</pre><pre>        │</pre><pre>        ▼</pre><pre>Kernel Driver</pre><pre>Stores</pre><pre>&quot;hello&quot;</pre><pre>inside kernel memory</pre><pre>        │</pre><pre>        ▼</pre><pre>cat /dev/mybuf</pre><pre>        │</pre><pre>        ▼</pre><pre>hello</pre><p>There’s no sensor.</p><p>No LED.</p><p>No display.</p><p>Just a small buffer.</p><p>That lets us focus entirely on understanding how Linux device drivers work.</p><h3>Looking at the Header Files</h3><p>Let’s begin with the includes.</p><pre>#include &lt;linux/init.h&gt;<br>#include &lt;linux/module.h&gt;<br>#include &lt;linux/kernel.h&gt;<br>#include &lt;linux/fs.h&gt;<br>#include &lt;linux/cdev.h&gt;<br>#include &lt;linux/device.h&gt;<br>#include &lt;linux/uaccess.h&gt;<br>#include &lt;linux/ioctl.h&gt;<br>#include &lt;linux/string.h&gt;</pre><p>Some of these are familiar.</p><p>Some are completely new.</p><p>Let’s understand why we need each one.</p><h3>linux/init.h</h3><p>Just like the previous articles,</p><pre>__init</pre><p>and</p><pre>__exit</pre><p>come from here.</p><p>These macros tell Linux which functions are used only during loading and unloading.</p><h3>linux/module.h</h3><p>Provides everything needed to create a kernel module.</p><p>Without this header we couldn’t use</p><pre>module_init()<br>module_exit()<br>MODULE_LICENSE()<br>MODULE_AUTHOR()</pre><h3>linux/kernel.h</h3><p>Provides common kernel utilities.</p><p>Most importantly,</p><pre>printk()</pre><p>which we’ve already used several times.</p><h3>linux/fs.h</h3><p>This is our first new header.</p><p>The letters <strong>fs</strong> stand for <strong>File System</strong>.</p><p>Remember what we said earlier?</p><p>Linux treats devices like files.</p><p>This header contains the definitions needed for file operations such as</p><ul><li>read</li><li>write</li><li>open</li><li>close</li></ul><p>Without it, Linux wouldn’t know that our driver behaves like a file.</p><h3>linux/cdev.h</h3><p>This header introduces a completely new concept.</p><pre>cdev</pre><p>stands for</p><p><strong>Character Device</strong>.</p><p>This structure represents our driver inside the kernel.</p><p>Think of it as Linux’s internal record for our device.</p><p>Later we’ll register it with the kernel.</p><h3>linux/device.h</h3><p>Creating a driver isn’t enough.</p><p>Users also need a device file.</p><p>This header allows us to create</p><pre>/dev/mybuf</pre><p>automatically.</p><p>Without it, we’d have to create device nodes manually.</p><p>Linux can do that work for us.</p><h3>linux/uaccess.h</h3><p>We’ve already seen</p><pre>copy_to_user()</pre><p>in Part 2.</p><p>Now we’ll also use</p><pre>copy_from_user()</pre><p>This header provides both.</p><p>They safely move data between</p><pre>User Space</pre><pre>↓</pre><pre>Kernel Space</pre><p>and back again.</p><h3>linux/ioctl.h</h3><p>Later we’ll introduce</p><pre>ioctl()</pre><p>Think of it as a special command channel.</p><p>Sometimes reading and writing isn’t enough.</p><p>Applications may want to send commands like</p><ul><li>reset</li><li>configure</li><li>enable</li><li>disable</li></ul><p>That’s exactly what ioctl() is designed for.</p><h3>linux/string.h</h3><p>Our driver resets its internal buffer using</p><pre>memset()</pre><p>This function comes from</p><pre>linux/string.h</pre><h3>Giving Our Device a Name</h3><p>Near the top of the file we define</p><pre>#define DEVICE_NAME &quot;mybuf&quot;</pre><p>Later,</p><p>Linux will create</p><pre>/ dev / mybuf</pre><p>(Without the spaces.)</p><p>Changing this macro changes the device name everywhere in the driver.</p><p>Using a macro avoids repeating the same string multiple times.</p><h3>How Big Is Our Buffer?</h3><p>Next,</p><pre>#define BUF_SIZE 32</pre><p>Our driver stores data inside a fixed-size buffer.</p><pre>+--------------------------------+<br>|                                |<br>|        32 Bytes                |<br>|                                |<br>+--------------------------------+</pre><p>If someone writes more than 32 bytes,</p><p>our driver simply ignores the extra data.</p><p>Keeping the first driver small makes it much easier to understand.</p><p>We’ll remove this limitation in future articles.</p><h3>Introducing ioctl</h3><p>The next lines look a little unusual.</p><pre>#define MYBUF_IOC_MAGIC &#39;k&#39;<br>#define MYBUF_RESET _IO(MYBUF_IOC_MAGIC, 0)</pre><p>Don’t worry if these macros seem confusing.</p><p>For now, think of them as creating a unique command.</p><p>Later,</p><p>a user-space application can tell the driver</p><blockquote><em>“Reset your buffer.”</em></blockquote><p>instead of writing data to it.</p><p>We’ll explore ioctl() in much greater detail later in this series.</p><p>For now, just remember one thing.</p><p>Our driver already supports its first custom command.</p><h3>The Driver’s Memory</h3><p>Now we reach the heart of the driver.</p><pre>static char kbuffer[BUF_SIZE];</pre><p>Unlike a normal application,</p><p>this memory belongs to the Linux kernel.</p><p>Everything written into /dev/mybuf</p><p>will eventually be stored here.</p><p>Next,</p><pre>static int data_len = 0;</pre><p>tracks how many bytes inside the buffer are actually valid.</p><p>Imagine the buffer looks like this.</p><pre>+--------------------------------+<br>| h | e | l | l | o | ? | ? | ? |<br>+--------------------------------+</pre><pre>data_len = 5</pre><p>Although the buffer can hold 32 bytes,</p><p>only the first five currently contain useful data.</p><p>The remaining space is unused.</p><h3>Linux Needs an Identity for Every Device</h3><p>Every device in Linux has two numbers.</p><ul><li>Major Number</li><li>Minor Number</li></ul><p>Together they uniquely identify a device.</p><p>Inside our driver we declare</p><pre>static dev_t dev_num;</pre><p>Later,</p><p>Linux will fill this variable with both numbers.</p><p>Think of it like this.</p><pre>Device</pre><pre>↓</pre><pre>Major Number<br>Which driver?</pre><pre>↓</pre><pre>Minor Number<br>Which device?</pre><p>If one driver manages four identical sensors,</p><p>they all have the same major number.</p><p>The minor number tells Linux which individual sensor we’re talking about.</p><h3>Representing Our Character Device</h3><p>Next,</p><pre>static struct cdev my_cdev;</pre><p>Earlier we learned that</p><pre>cdev</pre><pre>=</pre><pre>Character Device</pre><p>This structure connects our driver with Linux’s Virtual File System.</p><p>Once registered,</p><p>Linux knows that</p><pre>/ dev / mybuf</pre><p>belongs to our driver.</p><p>Whenever somebody opens the device,</p><p>Linux will eventually call our functions.</p><p>We’ll see exactly how that happens in Part 3B.</p><h3>Creating a Device Class</h3><p>The final global variable is</p><pre>static struct class *my_class;</pre><p>At first glance,</p><p>this seems unrelated.</p><p>But it plays an important role.</p><p>Modern Linux systems automatically create device nodes inside /dev.</p><p>To do that,</p><p>Linux groups similar devices into <strong>classes</strong>.</p><p>Our driver creates one called</p><pre>mybuf</pre><p>Later,</p><p>this class helps Linux automatically create</p><pre>/ dev / mybuf</pre><p>Without it,</p><p>we would have to create the device manually using</p><pre>mknod</pre><p>Fortunately,</p><p>the kernel can do everything for us.</p><h3>What We’ve Built So Far</h3><p>Believe it or not,</p><p>we still haven’t written a single line of driver logic.</p><p>And that’s perfectly okay.</p><p>Before Linux can call our driver,</p><p>we first need to define</p><ul><li>what kind of device we’re creating,</li><li>how much memory it owns,</li><li>how Linux should identify it,</li><li>and how the device should appear inside /dev.</li></ul><p>These pieces form the foundation of every character device driver.</p><p>In the next part, we’ll finally connect our driver to Linux by implementing the famous <strong>file_operations</strong> structure.</p><p>That’s where things become really exciting.</p><p>We’ll watch Linux call our own open(), read(), write(), release(), and ioctl() functions whenever a user interacts with /dev/mybuf.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e15ea434857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Kernel Module Could Only Say “Hello”… So I Taught It to Have a Conversation]]></title>
            <link>https://medium.com/@aruncse2k20/my-kernel-module-could-only-say-hello-so-i-taught-it-to-have-a-conversation-f1bc42e1c713?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1bc42e1c713</guid>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[linux-driver]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[learn-linux-device-driver]]></category>
            <category><![CDATA[android-framework]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 19:20:50 GMT</pubDate>
            <atom:updated>2026-07-23T19:20:50.010Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2B — Bringing the Module to Life</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cF8UJ-s-ovcAVy0byJElZg.png" /></figure><p>In the first half of this article, we built a smarter kernel module.</p><p>It could now:</p><ul><li>Accept parameters while loading.</li><li>Create a virtual file inside /proc.</li><li>Remember when it was loaded.</li><li>Send information back to user space.</li></ul><p>But there was one problem.</p><p>None of this mattered unless we could actually run it.</p><p>So, just like in Part 1, it’s time to open the terminal and see our module come alive.</p><h3>Our Workspace</h3><p>Before building anything, I checked what was inside my project directory.</p><pre>arun@raspberrypi:~/LKI/module2 $ ls</pre><p>The output was simple.</p><pre>Makefile<br>param_proc.c</pre><p>Exactly what I expected.</p><p>One source file.</p><p>One Makefile.</p><p>Nothing more.</p><p>Just like our first kernel module.</p><h3>Compiling the Module</h3><p>The next step was familiar.</p><pre>make</pre><p>The terminal responded with</p><pre>make -C /lib/modules/6.18.34+rpt-rpi-2712/build M=/home/arun/LKI/module2 modules</pre><pre>CC [M]  param_proc.o<br>MODPOST Module.symvers<br>CC [M]  param_proc.mod.o<br>CC [M]  .module-common.o<br>LD [M]  param_proc.ko</pre><p>If you read Part 1, these lines should already look familiar.</p><p>Let’s quickly revisit what each one means.</p><h3>CC</h3><pre>CC [M] param_proc.o</pre><p>The C compiler compiled our source code.</p><pre>param_proc.c</pre><pre>        ↓</pre><pre>param_proc.o</pre><p>This is an object file.</p><p>It isn’t a kernel module yet.</p><p>It’s simply the compiled version of our source code.</p><h3>MODPOST</h3><p>Next came</p><pre>MODPOST Module.symvers</pre><p>This is a special step performed by the Linux kernel build system.</p><p>During this phase, Linux checks module metadata.</p><p>It also prepares symbol information so that the kernel knows which functions our module uses and exports.</p><p>You don’t normally need to think about this step, but it’s happening every time you build a kernel module.</p><h3>LD</h3><p>Finally,</p><pre>LD [M] param_proc.ko</pre><p>This is the step we’ve been waiting for.</p><p>The linker combines everything together and produces</p><pre>param_proc.ko</pre><p>Remember from Part 1:</p><p>.ko stands for <strong>Kernel Object</strong>.</p><p>This is the file that can actually be loaded into the running Linux kernel.</p><h3>What Changed?</h3><p>Before compiling, our directory contained only two files.</p><p>After running make, I checked again.</p><pre>ls</pre><p>This time I saw</p><pre>Makefile<br>Module.symvers<br>modules.order<br>param_proc.c<br>param_proc.ko<br>param_proc.mod<br>param_proc.mod.c<br>param_proc.mod.o<br>param_proc.o</pre><p>That’s quite a few new files.</p><p>Most of them are generated automatically by the kernel build system.</p><p>For now, only one file really matters.</p><pre>param_proc.ko</pre><p>Everything else is supporting build output.</p><h3>Loading the Module</h3><p>Now came the exciting part.</p><p>I loaded the module into the running kernel.</p><pre>sudo insmod param_proc.ko</pre><p>Unlike Part 1, there was no visible output.</p><p>The terminal simply returned.</p><p>Did it actually work?</p><p>There was only one way to find out.</p><h3>Asking the Kernel</h3><p>Whenever a kernel module prints a message using</p><pre>printk()</pre><p>the message is stored inside the kernel log buffer.</p><p>We can read it using</p><pre>dmesg</pre><p>So I typed</p><pre>dmesg</pre><p>Among the previous messages, I found this line.</p><pre>param_proc: loaded with count=1 name=Arun</pre><p>Success!</p><p>Our module was now running inside the kernel.</p><p>Even better, it showed the default values of our module parameters.</p><pre>count = 1</pre><pre>name = Arun</pre><p>Remember these values.</p><p>We’ll change them later without modifying the source code.</p><h3>Is the Module Really Loaded?</h3><p>Kernel messages are nice.</p><p>But I wanted stronger proof.</p><p>Linux provides another command for that.</p><pre>lsmod</pre><p>This command lists every kernel module currently loaded.</p><p>I ran</p><pre>lsmod | head -5</pre><p>and saw</p><pre>Module                  Size  Used by</pre><pre>param_proc             49152  0</pre><p>There it was.</p><p>Our module had officially joined the running Linux kernel.</p><p>The number</p><pre>49152</pre><p>shows the amount of kernel memory occupied by the module.</p><p>The final</p><pre>0</pre><p>means that no other kernel component is currently using it.</p><h3>Learning About a Module Without Reading Its Source Code</h3><p>Suppose someone gives you a .ko file.</p><p>You don’t have the source code.</p><p>How do you know</p><ul><li>who wrote it?</li><li>what license it uses?</li><li>what parameters it accepts?</li><li>what kernel version it supports?</li></ul><p>Linux has a tool for exactly this purpose.</p><pre>modinfo</pre><p>I ran</p><pre>modinfo param_proc.ko</pre><p>The output was</p><pre>description: Module params + /proc entry demo<br>author: Arun<br>license: GPL</pre><pre>parm: count:Number of greetings (int)<br>parm: name:Name to greet (charp)</pre><p>This was a nice moment.</p><p>Remember these lines from our source code?</p><pre>MODULE_AUTHOR(&quot;Arun&quot;);<br>MODULE_DESCRIPTION(&quot;Module params + /proc entry demo&quot;);</pre><pre>MODULE_PARM_DESC(count, &quot;Number of greetings&quot;);<br>MODULE_PARM_DESC(name, &quot;Name to greet&quot;);</pre><p>Now we could finally see where they appeared.</p><p>The information we added wasn’t just for documentation.</p><p>Linux actually stores it inside the module.</p><p>Whenever someone runs modinfo, those details are displayed automatically.</p><h3>Reading From /proc</h3><p>Now it was time to try the feature we built.</p><p>Our module had created a virtual file called</p><pre>/proc/param_proc_demo</pre><p>Unlike a normal file, this file doesn’t exist on disk.</p><p>It exists only while our module is loaded.</p><p>I read it using</p><pre>cat /proc/param_proc_demo</pre><p>The output was</p><pre>Loaded 68525 jiffies ago</pre><pre>Hello, Arun! (1)</pre><p>Something amazing just happened.</p><p>The cat command looked completely ordinary.</p><p>But behind the scenes, Linux executed our function</p><pre>param_proc_read()</pre><p>Our code generated the output.</p><p>Then</p><pre>copy_to_user()</pre><p>copied that information into user space.</p><p>Finally,</p><p>cat</p><p>displayed it on the terminal.</p><p>A simple command triggered our kernel code.</p><p>That’s one of the coolest things about Linux kernel development.</p><h3>Removing the Module</h3><p>Every module should clean up after itself.</p><p>I unloaded it using</p><pre>sudo rmmod param_proc</pre><p>Then checked the kernel log again.</p><pre>dmesg</pre><p>Near the bottom I found</p><pre>param_proc: unloaded</pre><p>Exactly what we expected.</p><p>Our cleanup function had executed successfully.</p><p>The /proc file disappeared automatically because</p><pre>proc_remove(proc_entry);</pre><p>was called during module removal.</p><h3>Changing the Module Without Changing the Code</h3><p>Until now, our module had used the default values.</p><pre>count = 1</pre><pre>name = Arun</pre><p>But remember why we introduced module parameters?</p><p>So that we wouldn’t have to edit the source code every time.</p><p>Let’s try that now.</p><p>Instead of simply loading the module, I passed two parameters.</p><pre>sudo insmod param_proc.ko count=3 name=&quot;RPi5&quot;</pre><p>Notice something interesting.</p><p>I didn’t recompile anything.</p><p>I didn’t change the source code.</p><p>I simply passed new values while loading the module.</p><p>Checking the kernel log again,</p><pre>dmesg</pre><p>showed</p><pre>param_proc: loaded with count=3 name=RPi5</pre><p>The kernel had accepted our new configuration.</p><h3>Reading /proc Again</h3><p>Now I was curious.</p><p>Would the /proc file also reflect these new values?</p><p>I typed</p><pre>cat /proc/param_proc_demo</pre><p>The output was</p><pre>Loaded 5821 jiffies ago</pre><pre>Hello, RPi5! (1)</pre><pre>Hello, RPi5! (2)</pre><pre>Hello, RPi5! (3)</pre><p>Exactly as expected.</p><p>The same kernel module behaved differently simply because we changed its parameters.</p><p>That’s the real power of module_param().</p><h3>Where Does Linux Store These Parameters?</h3><p>Earlier, I mentioned that module parameters are exposed through <strong>sysfs</strong>.</p><p>Let’s see that ourselves.</p><p>I typed</p><pre>cat /sys/module/param_proc/parameters/count</pre><p>The output was</p><pre>3</pre><p>Then</p><pre>cat /sys/module/param_proc/parameters/name</pre><p>returned</p><pre>RPi5</pre><p>This is another fascinating Linux feature.</p><p>Our module parameters automatically appear inside</p><pre>/sys/module/</pre><p>without us writing any extra code.</p><p>Think of it this way.</p><pre>Module Parameter</pre><pre>        │</pre><pre>        ▼</pre><pre>Kernel</pre><pre>        │</pre><pre>Automatically</pre><pre>        ▼</pre><pre>/sys/module/param_proc/parameters/</pre><p>Linux does all the hard work for us.</p><h3>One More Experiment</h3><p>I wanted to see what would happen if I loaded the module with</p><pre>count=0</pre><p>So I unloaded the module first.</p><pre>sudo rmmod param_proc</pre><p>Then loaded it again.</p><pre>sudo insmod param_proc.ko count=0</pre><p>Finally,</p><pre>cat /proc/param_proc_demo</pre><p>The output became</p><pre>Loaded 2667 jiffies ago</pre><p>There were no greetings.</p><p>Why?</p><p>Because of this loop.</p><pre>for (i = 0; i &lt; count; i++)</pre><p>If</p><pre>count = 0</pre><p>the loop never executes.</p><p>No iterations.</p><p>No greetings.</p><p>The module behaved exactly as our code described.</p><h3>Looking Back</h3><p>Compared to our first kernel module, we’ve learned an incredible amount.</p><p>Our module can now</p><ul><li>Accept parameters during loading.</li><li>Describe those parameters using modinfo.</li><li>Create its own virtual file in /proc.</li><li>Return information to user space.</li><li>Measure how long it has been loaded using jiffies.</li><li>Expose configuration automatically through /sys/module.</li><li>Change its behaviour without recompiling.</li></ul><p>That’s a huge step forward.</p><p>But despite all this…</p><p>We still haven’t written a real Linux device driver.</p><p>Our module still doesn’t create a device file.</p><p>It doesn’t respond to</p><ul><li>open()</li><li>read()</li><li>write()</li><li>close()</li></ul><p>Those are the operations that allow user applications to communicate directly with kernel drivers.</p><p>And that’s exactly where our journey goes next.</p><h3>What’s Next?</h3><p>So far, we’ve learned how to load a module, pass parameters to it, and communicate through /proc.</p><p>In the next article, we’ll take the next big step.</p><p>We’ll build our <strong>first Character Device Driver</strong>.</p><p>Instead of reading a file under /proc, we&#39;ll create our own device file under /dev, implement the famous file_operations structure, and watch user-space applications communicate directly with our kernel code.</p><p>That’s where Linux device drivers start to feel like real software.</p><p>See you in Part 3.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1bc42e1c713" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Kernel Module Could Only Say “Hello”… So I Taught It to Have a Conversation]]></title>
            <link>https://medium.com/@aruncse2k20/my-kernel-module-could-only-say-hello-so-i-taught-it-to-have-a-conversation-c9497beb49a9?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9497beb49a9</guid>
            <category><![CDATA[kernel-driver]]></category>
            <category><![CDATA[driver-tutorial]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 18:33:23 GMT</pubDate>
            <atom:updated>2026-07-22T18:33:23.742Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of my Linux Device Driver Journey on Raspberry Pi 5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41HUdWPIsn-0tYF0n_2Bfg.png" /></figure><blockquote><em>“In the previous article, our kernel module could only say ‘Hello.’ In this article, we’ll make it listen, remember, and respond.”</em></blockquote><p>If you haven’t read Part 1, here’s a quick recap.</p><p>We wrote our very first Linux kernel module.</p><p>It was only a few lines of code.</p><p>When we loaded it into the Linux kernel using insmod, it printed:</p><pre>Hello from RPi5 kernel module!</pre><p>When we removed it using rmmod, it printed:</p><pre>Goodbye from RPi5 kernel module!</pre><p>It felt amazing.</p><p>Our code was no longer running as a normal application.</p><p>It was running inside the Linux kernel.</p><p>But after the excitement settled down, I realized something.</p><p>Our module wasn’t very smart.</p><p>It always printed exactly the same message.</p><p>No matter who loaded it…</p><p>No matter when it was loaded…</p><p>No matter what I wanted…</p><p>It always behaved the same way.</p><p>That raised an interesting question.</p><h3>What if I wanted to change its behaviour?</h3><p>Suppose tomorrow I wanted it to greet me three times.</p><pre>Hello, Arun!<br>Hello, Arun!<br>Hello, Arun!</pre><p>Or maybe I wanted it to greet someone else.</p><pre>Hello, Raspberry Pi!</pre><p>Should I edit the source code every time?</p><p>Compile again?</p><p>Create a new .ko file?</p><p>Unload the old module?</p><p>Load the new one?</p><p>That would become frustrating very quickly.</p><p>Fortunately, Linux already has a solution.</p><p>It’s called <strong>Module Parameters</strong>.</p><h3>Module Parameters</h3><p>Think about command-line applications.</p><p>When we execute a command like</p><pre>ping google.com</pre><p>we are passing an argument to the program.</p><p>Similarly, Linux allows us to pass arguments while loading a kernel module.</p><p>Instead of hardcoding everything inside the source code, we can configure the module when it is loaded.</p><p>Let’s see how.</p><h3>Two Variables That Control Our Module</h3><p>Near the beginning of the module, we have two variables.</p><pre>static int count = 1;<br>static char *name = &quot;Arun&quot;;</pre><p>These two variables decide how our module behaves.</p><p>The first one,</p><pre>count</pre><p>stores how many greetings we want.</p><p>By default, it is set to</p><pre>1</pre><p>The second variable,</p><pre>name</pre><p>stores the name that should appear in the greeting.</p><p>By default,</p><pre>Arun</pre><p>will be printed.</p><p>Right now they are just ordinary C variables.</p><p>Linux doesn’t know anything about them yet.</p><p>We need to expose them as <strong>module parameters</strong>.</p><h3>Introducing module_param()</h3><p>The next lines do exactly that.</p><pre>module_param(count, int, 0644);<br>module_param(name, charp, 0644);</pre><p>Although these lines look small, they are incredibly powerful.</p><p>Let’s break one of them into pieces.</p><pre>module_param(count, int, 0644);</pre><p>The first argument</p><pre>count</pre><p>is the variable name.</p><p>The second argument</p><pre>int</pre><p>tells Linux that this parameter is an integer.</p><p>The third argument</p><pre>0644</pre><p>defines the file permissions when Linux exposes this parameter through <strong>sysfs</strong>.</p><p>If you’ve used Linux before, you’ve probably seen permissions like</p><pre>-rw-r--r--</pre><p>The number 0644 represents the same permissions.</p><ul><li>Owner can read and write.</li><li>Group can only read.</li><li>Others can only read.</li></ul><p>We don’t have to worry too much about permissions yet.</p><p>For now, just remember that Linux treats module parameters almost like regular files.</p><h3>Adding a Description</h3><p>The next two lines are</p><pre>MODULE_PARM_DESC(count, &quot;Number of greetings&quot;);<br>MODULE_PARM_DESC(name, &quot;Name to greet&quot;);</pre><p>These lines don’t change how the module works.</p><p>Instead, they add documentation.</p><p>Think of them as labels.</p><p>Later, when we run the command</p><pre>modinfo param_proc.ko</pre><p>Linux will show these descriptions automatically.</p><p>We’ll see that in action later in this article.</p><h3>Our Module Needs Memory</h3><p>Next, we declare two more variables.</p><pre>static struct proc_dir_entry *proc_entry;<br>static unsigned long load_jiffies;</pre><p>These are completely different from the module parameters.</p><p>The first variable,</p><pre>proc_entry</pre><p>stores information about the file we are going to create inside the /proc filesystem.</p><p>The second variable,</p><pre>load_jiffies</pre><p>remembers <strong>when the module was loaded</strong>.</p><p>But what exactly are <strong>jiffies</strong>?</p><h3>What Are Jiffies?</h3><p>Imagine that the Linux kernel has its own clock.</p><p>Every tiny tick of that clock increases a variable called</p><pre>jiffies</pre><p>You can think of it like this.</p><pre>Kernel starts</pre><pre>jiffies = 0</pre><pre>↓</pre><pre>Tick...</pre><pre>jiffies = 1</pre><pre>↓</pre><pre>Tick...</pre><pre>jiffies = 2</pre><pre>↓</pre><pre>Tick...</pre><pre>jiffies = 3</pre><pre>↓</pre><pre>...</pre><p>The number keeps increasing for as long as the system is running.</p><p>When our module loads, we save the current value.</p><pre>load_jiffies = jiffies;</pre><p>Later, if we calculate</p><pre>jiffies - load_jiffies</pre><p>we get</p><blockquote><em>“How long has this module been alive?”</em></blockquote><p>That’s exactly what we’ll display through /proc.</p><h3>Printing Messages Is Not Enough</h3><p>In Part 1, we used</p><pre>printk()</pre><p>to send messages to the kernel log.</p><p>That worked well.</p><p>But there was one problem.</p><p>Those messages only appeared once.</p><p>After that, the module became silent.</p><p>What if we wanted to ask the module questions whenever we liked?</p><p>For example,</p><ul><li>How long have you been loaded?</li><li>What’s your current configuration?</li><li>What’s your current status?</li></ul><p>We need a better way to communicate.</p><p>Linux gives us one.</p><p>The <strong>/proc filesystem</strong>.</p><h3>What Is /proc?</h3><p>The /proc directory is not a normal directory.</p><p>The files inside it don’t actually exist on the disk.</p><p>They are created by the kernel while the system is running.</p><p>Whenever you read one of those files, the kernel generates the contents on demand.</p><p>You can think of it like this.</p><pre>User Space</pre><pre>cat /proc/some_file</pre><pre>        │</pre><pre>        ▼</pre><pre>Linux Kernel</pre><pre>Generates the data</pre><pre>        │</pre><pre>        ▼</pre><pre>Shows it to the user</pre><p>Instead of storing information permanently, /proc acts like a live window into the kernel.</p><p>Our module is about to create its own file there.</p><h3>Reading From /proc</h3><p>The most important function in this module is</p><pre>static ssize_t param_proc_read(...)</pre><p>This function is executed every time someone runs</p><pre>cat /proc/param_proc_demo</pre><p>In other words,</p><p>reading the file causes the kernel to call this function.</p><p>That’s a fascinating idea.</p><p>A simple cat command in user space ends up executing our C code inside the Linux kernel.</p><h3>Why Do We Check the Offset?</h3><p>One of the first lines is</p><pre>if (*offset &gt; 0)<br>    return 0;</pre><p>At first, this looks strange.</p><p>Why return zero?</p><p>The answer lies in how Linux reads files.</p><p>Programs like cat may call the read function multiple times.</p><p>If we kept returning the same data forever, cat would never know when to stop.</p><p>Returning</p><pre>0</pre><p>tells Linux,</p><blockquote><em>“End of file.”</em></blockquote><p>Without this check, cat would continue reading forever.</p><h3>Building the Output</h3><p>Next, we create a buffer.</p><pre>char msg[256];</pre><p>Think of this as a temporary notebook.</p><p>We’ll write all our messages into it before sending them to user space.</p><p>The first message is</p><pre>Loaded %lu jiffies ago</pre><p>This is calculated using</p><pre>jiffies - load_jiffies</pre><p>Immediately after that, we enter a loop.</p><pre>for (i = 0; i &lt; count; i++)</pre><p>This loop runs exactly as many times as the value of count.</p><p>If</p><pre>count = 1</pre><p>we get</p><pre>Hello, Arun! (1)</pre><p>If</p><pre>count = 3</pre><p>we get</p><pre>Hello, Arun! (1)<br>Hello, Arun! (2)<br>Hello, Arun! (3)</pre><p>Notice that we didn’t change a single line of code.</p><p>Only the parameter changed.</p><h3>The Most Important Function</h3><p>Finally, we encounter one of the most important functions in Linux kernel programming.</p><pre>copy_to_user()</pre><p>Why can’t we simply return our buffer?</p><p>Because kernel memory and user memory are completely separate.</p><pre>+----------------------+<br>|     User Space       |<br>|      cat command     |<br>+----------------------+</pre><pre>           ▲</pre><pre>copy_to_user()</pre><pre>           ▼</pre><pre>+----------------------+<br>|    Kernel Space      |<br>|      msg[] buffer    |<br>+----------------------+</pre><p>The kernel cannot simply hand its memory to user programs.</p><p>Instead, it safely copies the data from kernel space into user space.</p><p>That is exactly what copy_to_user() does.</p><p>You’ll see this function again and again while writing Linux device drivers.</p><p>It’s one of the most fundamental APIs in kernel development.</p><h3>Telling Linux How to Read Our File</h3><p>Next, we define</p><pre>static const struct proc_ops param_proc_fops = {<br>    .proc_read = param_proc_read,<br>};</pre><p>Think of this as a menu.</p><p>Whenever someone reads our /proc file, Linux looks here.</p><p>It finds</p><pre>.proc_read</pre><p>and immediately calls</p><pre>param_proc_read()</pre><p>It’s the bridge between the virtual file and our code.</p><h3>Creating Our /proc File</h3><p>Inside the module’s initialization function, we finally create the file.</p><pre>proc_entry = proc_create(<br>    &quot;param_proc_demo&quot;,<br>    0444,<br>    NULL,<br>    &amp;param_proc_fops<br>);</pre><p>Let’s understand each argument.</p><p>The first argument,</p><pre>&quot;param_proc_demo&quot;</pre><p>becomes the filename.</p><p>Our module creates</p><pre>/proc/param_proc_demo</pre><p>The second argument,</p><pre>0444</pre><p>means the file is read-only.</p><p>The third argument,</p><pre>NULL</pre><p>tells Linux to create it in the root of the /proc directory.</p><p>The final argument,</p><pre>&amp;param_proc_fops</pre><p>connects the file with our read function.</p><p>Whenever someone reads the file, Linux knows exactly which function to execute.</p><h3>Remembering When We Loaded</h3><p>Just before creating the /proc entry, we save</p><pre>load_jiffies = jiffies;</pre><p>From that moment onward, our module remembers when it entered the kernel.</p><p>Every time someone reads/proc/param_proc_demo, the kernel calculates how long the module has been alive.</p><p>A tiny feature — but a very useful one.</p><h3>Cleaning Up</h3><p>Just like Part 1, every initialization should have a cleanup.</p><pre>proc_remove(proc_entry);</pre><p>This removes our virtual file from the /proc filesystem.</p><p>If we forget to do this, Linux would be left with an invalid entry pointing to a module that no longer exists.</p><p>Cleaning up is just as important as creating resources.</p><h3>What We Built</h3><p>Compared to our first kernel module, this one is much more capable.</p><p>It can now:</p><ul><li>Accept parameters while loading.</li><li>Remember when it was loaded.</li><li>Create its own file inside /proc.</li><li>Generate information on demand.</li><li>Safely copy data from kernel space to user space.</li></ul><p>And the best part?</p><p>We still haven’t written a real device driver.</p><p>We’re simply learning the building blocks that almost every Linux driver uses.</p><p>In the next part, we’ll compile this module, load it into the kernel, inspect it with modinfo, read data from /proc, explore /sys/module, and see how changing module parameters completely changes our module&#39;s behaviour without touching a single line of code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9497beb49a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Said “Hello” to the Linux Kernel — And It Talked Back]]></title>
            <link>https://medium.com/@aruncse2k20/i-said-hello-to-the-linux-kernel-and-it-talked-back-2be6153d7839?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be6153d7839</guid>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[driver-tutorial]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[linux-driver]]></category>
            <category><![CDATA[kernel-driver]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 17:10:19 GMT</pubDate>
            <atom:updated>2026-07-22T17:10:19.490Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of my Linux Device Driver Journey on Raspberry Pi 5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_XdfUIcJwDnnE9R9ydWyg.png" /></figure><blockquote><em>“Every Linux device driver starts with something incredibly simple — not controlling hardware, not handling interrupts, not talking to sensors. It starts by saying </em><strong><em>Hello</em></strong><em>.”</em></blockquote><p>For a long time, Linux kernel development looked mysterious to me.</p><p>I had written Android applications for years. If I wanted to print something, I used Log.d(). If I wanted to build my project, Android Studio did everything for me.</p><p>Kernel development felt completely different.</p><p>There was no Android Studio.<br>No Run button.<br>No Emulator.</p><p>Just a terminal, a Raspberry Pi 5, and a small C file.</p><p>This article is the first in my Linux Device Driver learning series. My goal isn’t just to teach Linux drivers — it’s to document my own journey, one experiment at a time.</p><p>So let’s begin with the smallest possible kernel module.</p><h3>What Exactly Is a Kernel Module?</h3><p>Before writing any code, let’s answer one question.</p><p><strong>What is a kernel module?</strong></p><p>Think of the Linux kernel as the brain of the operating system.</p><p>Normally, the kernel is already running. We don’t rebuild or restart it every time we want to add a new feature.</p><p>Instead, Linux allows us to load small pieces of code into the running kernel.</p><p>Those pieces are called <strong>Kernel Modules</strong>.</p><p>You can think of them like plugins.</p><p>Instead of modifying the entire kernel, we simply plug in our module when we need it and unplug it when we’re done.</p><p>Most device drivers in Linux are implemented as kernel modules.</p><p>That makes this tiny “Hello World” module the perfect starting point.</p><h3>Writing Our First Kernel Module</h3><p>I created a file named <strong>hello.c</strong>.</p><pre>#include &lt;linux/init.h&gt;<br>#include &lt;linux/module.h&gt;<br>#include &lt;linux/kernel.h&gt;</pre><pre>static int __init hello_init(void)<br>{<br>    printk(KERN_INFO &quot;Hello from RPi5 kernel module!\n&quot;);<br>    return 0;<br>}</pre><pre>static void __exit hello_exit(void)<br>{<br>    printk(KERN_INFO &quot;Goodbye from RPi5 kernel module!\n&quot;);<br>}</pre><pre>module_init(hello_init);<br>module_exit(hello_exit);</pre><pre>MODULE_LICENSE(&quot;GPL&quot;);</pre><p>At first glance, it doesn’t look very different from a normal C program.</p><p>But every line has a purpose.</p><p>Let’s understand it.</p><h3>The Header Files</h3><pre>#include &lt;linux/init.h&gt;</pre><p>This header provides helper macros such as __init and __exit.</p><p>These tell the kernel when these functions are used.</p><pre>#include &lt;linux/module.h&gt;</pre><p>This header provides everything needed for creating a kernel module.</p><p>Without it, functions like</p><pre>module_init()<br>module_exit()<br>MODULE_LICENSE()</pre><p>would not exist.</p><pre>#include &lt;linux/kernel.h&gt;</pre><p>This provides kernel helper functions.</p><p>One of the most famous ones is</p><pre>printk()</pre><p>which is the kernel’s version of printf().</p><h3>The Module Entry Function</h3><pre>static int __init hello_init(void)</pre><p>This function runs <strong>exactly once</strong>.</p><p>It is executed when the module is loaded into the kernel.</p><p>Inside it we have</p><pre>printk(KERN_INFO &quot;Hello from RPi5 kernel module!\n&quot;);</pre><p>Unlike user-space programs, we cannot use</p><pre>printf()</pre><p>because the kernel has no standard output terminal.</p><p>Instead, we use</p><pre>printk()</pre><p>which writes messages into the kernel log buffer.</p><p>Later, we’ll read those messages using the dmesg command.</p><p>Finally,</p><pre>return 0;</pre><p>tells Linux that the module loaded successfully.</p><h3>The Module Exit Function</h3><pre>static void __exit hello_exit(void)</pre><p>This function runs when the module is removed from memory.</p><p>Here we simply print</p><pre>Goodbye from RPi5 kernel module!</pre><p>so that we know our cleanup function actually executed.</p><h3>Telling Linux Where to Start</h3><p>Near the bottom of the file we have</p><pre>module_init(hello_init);</pre><p>This tells Linux,</p><blockquote><em>“When this module is loaded, call hello_init().”</em></blockquote><p>Similarly,</p><pre>module_exit(hello_exit);</pre><p>tells Linux,</p><blockquote><em>“When this module is removed, call hello_exit().”</em></blockquote><h3>The License</h3><p>Finally,</p><pre>MODULE_LICENSE(&quot;GPL&quot;);</pre><p>This tells the kernel that our module uses the GPL license.</p><p>Without it, Linux marks the module as proprietary and may restrict access to certain kernel symbols.</p><p>For learning purposes, almost every tutorial uses GPL.</p><h3>Writing the Makefile</h3><p>The kernel module can’t be compiled using a normal</p><pre>gcc hello.c</pre><p>Instead, we let the Linux kernel build system compile it.</p><p>For that, we create a file named <strong>Makefile</strong>.</p><pre>obj-m += hello.o</pre><pre>KDIR := /lib/modules/$(shell uname -r)/build</pre><pre>all:<br>	make -C $(KDIR) M=$(PWD) modules</pre><pre>clean:<br>	make -C $(KDIR) M=$(PWD) clean</pre><p>Let’s understand it.</p><h3>obj-m += hello.o</h3><p>This tells the kernel build system,</p><blockquote><em>“Build hello.c as a loadable kernel module.”</em></blockquote><p>The output will eventually become</p><pre>hello.ko</pre><p>where <strong>.ko</strong> means <strong>Kernel Object</strong>.</p><h3>KDIR</h3><pre>KDIR := /lib/modules/$(shell uname -r)/build</pre><p>This points to the kernel headers for the currently running kernel.</p><p>Notice the command</p><pre>uname -r</pre><p>On my Raspberry Pi 5, it returned</p><pre>6.18.34+rpt-rpi-2712</pre><p>The Makefile automatically builds against the currently running kernel version.</p><h3>all</h3><pre>make</pre><p>actually executes</p><pre>make -C /lib/modules/.../build M=$(PWD) modules</pre><p>Here,</p><p>-C</p><p>means</p><blockquote><em>Change directory into the kernel build system.</em></blockquote><p>while</p><p>M=$(PWD)</p><p>tells the kernel</p><blockquote><em>“My module source code is in the current directory.”</em></blockquote><p>The kernel then compiles only our module.</p><h3>clean</h3><p>Later,</p><pre>make clean</pre><p>removes all generated files.</p><p>Only our original source code remains.</p><h3>Before Building</h3><p>I checked the directory.</p><pre>ls</pre><p>Output</p><pre>hello.c<br>Makefile</pre><p>Only two files existed.</p><p>Exactly what we created.</p><h3>Building the Module</h3><p>Now came the exciting part.</p><pre>make</pre><p>The output looked like this.</p><pre>CC [M] hello.o<br>MODPOST Module.symvers<br>CC [M] hello.mod.o<br>LD [M] hello.ko</pre><p>Let’s decode this.</p><h3>CC</h3><p>The compiler compiled</p><pre>hello.c</pre><p>into</p><pre>hello.o</pre><h3>MODPOST</h3><p>The kernel now checks module metadata.</p><p>It also creates</p><pre>Module.symvers</pre><p>which contains exported kernel symbols.</p><h3>LD</h3><p>Finally, the linker combines everything into</p><pre>hello.ko</pre><p>This is the file we can load into the Linux kernel.</p><h3>A Warning Appeared</h3><p>During compilation, I also saw</p><pre>WARNING: missing MODULE_DESCRIPTION()</pre><p>This isn’t an error.</p><p>The module still builds successfully.</p><p>It simply reminds us that we haven’t provided a description.</p><p>Later we can improve the module by adding</p><pre>MODULE_DESCRIPTION(&quot;My first kernel module&quot;);</pre><h3>What Changed After Compilation?</h3><p>Before compilation,</p><pre>hello.c<br>Makefile</pre><p>After compilation,</p><pre>hello.ko<br>hello.o<br>hello.mod.c<br>hello.mod.o<br>Module.symvers<br>modules.order</pre><p>The kernel build system generated several helper files.</p><p>Among all of them,</p><p><strong>hello.ko</strong></p><p>is the one we actually care about.</p><p>Everything else is intermediate build output.</p><h3>Cleaning Everything</h3><p>Next, I wanted to remove all generated files.</p><pre>make clean</pre><p>After that,</p><pre>ls</pre><p>again showed</p><pre>hello.c<br>Makefile</pre><p>Exactly back to where we started.</p><h3>Time to Talk to the Kernel</h3><p>Before loading the module, I wanted to clear the kernel log.</p><p>So I typed</p><pre>dmesg -C</pre><p>Instead of working, Linux replied</p><pre>Operation not permitted</pre><p>That surprised me.</p><p>Then I remembered something important.</p><p>The kernel belongs to the operating system.</p><p>Ordinary users aren’t allowed to modify kernel logs.</p><p>So I tried again.</p><pre>sudo dmesg -C</pre><p>This time it worked.</p><p>Checking the log</p><pre>dmesg</pre><p>returned nothing.</p><p>A completely clean log.</p><p>Perfect.</p><h3>Loading the Module</h3><p>Now came the real moment.</p><p>I tried</p><pre>insmod hello.ko</pre><p>Again,</p><p>Linux refused.</p><pre>Operation not permitted</pre><p>Of course.</p><p>Loading code into the running kernel is a privileged operation.</p><p>So I used</p><pre>sudo insmod hello.ko</pre><p>This time there was no output.</p><p>Did it work?</p><h3>Asking the Kernel</h3><p>I checked the kernel log.</p><pre>dmesg</pre><p>And there it was.</p><pre>Hello from RPi5 kernel module!</pre><p>That single line felt magical.</p><p>My code wasn’t running as a normal application.</p><p>It was running <strong>inside the Linux kernel</strong>.</p><h3>Is the Module Really Loaded?</h3><p>Let’s verify.</p><pre>lsmod</pre><p>This command lists every loaded kernel module.</p><p>I searched for mine.</p><pre>lsmod | grep hello</pre><p>Output</p><pre>hello 49152 0</pre><p>The module was officially part of the running kernel.</p><p>Mission accomplished.</p><h3>Removing the Module</h3><p>A kernel module should also clean up after itself.</p><p>So I unloaded it.</p><pre>sudo rmmod hello</pre><p>Then checked the log again.</p><pre>dmesg</pre><p>Output</p><pre>Hello from RPi5 kernel module!<br>Goodbye from RPi5 kernel module!</pre><p>Exactly as expected.</p><p>Our cleanup function executed successfully.</p><p>Finally,</p><pre>lsmod | grep hello</pre><p>returned nothing.</p><p>The module had disappeared from memory.</p><h3>What We Learned</h3><p>Although this module prints only two messages, we actually learned a lot.</p><p>We learned:</p><ul><li>What a Linux kernel module is</li><li>Why kernel modules are different from normal programs</li><li>How printk() works</li><li>Why module_init() and module_exit() exist</li><li>How the Linux kernel build system compiles modules</li><li>What hello.ko is</li><li>Why sudo is required for kernel operations</li><li>How to inspect loaded modules using lsmod</li><li>How to load a module using insmod</li><li>How to remove it using rmmod</li><li>How to read kernel logs using dmesg</li></ul><p>That’s quite a journey for fewer than 20 lines of C code.</p><h3>What’s Next?</h3><p>This tiny “Hello World” module is only the beginning.</p><p>In the next article, we’ll explore what actually happens behind the scenes when a kernel module is loaded. We’ll examine ELF sections, how the kernel invokesmodule_init(), and why a .ko file is very different from a normal executable.</p><p>One step at a time.</p><p>Because every complex Linux device driver begins with a simple “Hello.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be6153d7839" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wanted to See What My Android Was Thinking While It Woke Up]]></title>
            <link>https://medium.com/@aruncse2k20/i-wanted-to-see-what-my-android-was-thinking-while-it-woke-up-ce307f495e55?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce307f495e55</guid>
            <category><![CDATA[android-framework]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 13:52:26 GMT</pubDate>
            <atom:updated>2026-07-19T13:52:26.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sO40jxXASr8HpNheZX4U-Q.png" /></figure><h3>A story about chasing boot logs on AOSP, one method at a time</h3><p>A while back, I wrote about watching my Raspberry Pi wake up while it ran plain Linux — three different windows into the same quiet moment of a machine coming alive.</p><p>Then I flashed a different SD card into the same board. This one didn’t boot into a terminal prompt. It booted into something far more familiar — a home screen, app icons, a status bar. My Raspberry Pi 5 was now running <strong>AOSP</strong>, the same operating system that powers the phone in my pocket.</p><p>And I found myself asking the exact same question again, just in a very different house.</p><p><em>“How do I see what’s happening while this thing wakes up?”</em></p><p>I expected dmesg and journalctl to still be waiting for me, like old friends. But Android, it turns out, doesn&#39;t live in that world at all. It has its own language, its own habits, its own way of remembering what happened while it opened its eyes.</p><p>So I went looking again. And once more, I found three windows — but this time, each one looked completely different from what I knew before.</p><h3>Window One: adb shell dmesg — The Same Diary, a Different Door</h3><p>The first thing I reached for, out of habit, was dmesg. I typed it the way I always had — except this time, there was no SSH to get me in.</p><p>Android doesn’t run an SSH server. Instead, it speaks through a tool called <strong>ADB</strong> — the Android Debug Bridge. It’s the same idea as SSH, a way to reach into the device from my laptop, but it speaks Android’s language instead.</p><p>So I connected first:</p><pre>adb connect &lt;pi-ip&gt;:5555</pre><p>And then, instead of typing dmesg directly, I asked ADB to run it <em>for</em> me, inside the device:</p><pre>adb shell dmesg</pre><p>And there it was — the same kind of diary I remembered. Kernel messages, hardware detection, driver loading — Linux’s own private notes, still being written underneath all the Android magic layered on top. Because underneath every Android phone, every Android tablet, and now my little Raspberry Pi wearing an Android costume, there’s still a Linux kernel quietly doing its job.</p><p>It felt reassuring, in a way — like discovering an old friend was still living in the house, just behind a different front door.</p><p>But dmesg alone felt incomplete this time. Because Android isn&#39;t just a kernel with a few background services like plain Linux was. Android is a whole <em>world</em> built on top of that kernel — an entire framework of system services, animations, app processes — and none of that shows up in the kernel&#39;s private diary.</p><p>I needed a bigger book. And Android had one, but it wasn’t journalctl.</p><h3>Window Two: logcat — Android&#39;s Own Storyteller</h3><p>The bigger book was called logcat, and it turned out to be Android&#39;s own storyteller — one that had been narrating the entire boot sequence long before I ever thought to ask.</p><p>I typed:</p><pre>adb shell logcat</pre><p>And the flood of text that appeared was unlike anything I’d seen on plain Linux. It wasn’t just hardware and drivers anymore — it was the <strong>entire system waking up in layers</strong>. The Zygote process starting, ready to birth every app that would ever run. The System Server initializing dozens of framework services — one for power, one for windows, one for notifications, each announcing itself like a character walking onto a stage.</p><p>It read less like a diary and more like a play, with every actor introducing themselves as they entered.</p><p>I noticed something else, too — this storyteller didn’t just talk about the system. It talked about <em>everything</em>, all mixed together — my own apps, system apps, framework internals — all narrated in a single continuous stream, each line tagged with where it came from and how urgent it was.</p><p>That was a lot of noise for someone trying to find one specific thread. So I learned to ask the storyteller more specific questions.</p><p>If I only wanted the kernel’s part of the story, folded into this same narration:</p><pre>adb shell logcat -b kernel</pre><p>If I wanted to rewind and read only what had already happened, without the story continuing to scroll forever:</p><pre>adb shell logcat -d</pre><p>And when I was hunting for something specific — say, messages about my own hardware driver — I filtered the story down to just that character’s lines:</p><pre>adb shell logcat | grep mydriver</pre><p>Slowly, logcat stopped feeling like noise and started feeling like a very detailed, very honest narrator — one who simply told me everything, and trusted me to listen for what mattered.</p><p>But even this storyteller had a condition. It could only speak once a very specific listener was born inside Android — a small background service called logd, the log daemon. And logd, like every other actor in this play, doesn&#39;t exist from the very first second. It&#39;s born partway through boot, once Android&#39;s early init process has already done quite a bit of work.</p><p>Which meant, once again, I had found the edge of what these tools could show me.</p><h3>Window Three: The Serial Console — Watching Before Android Was Born</h3><p>I remembered this feeling from before. <em>If the story hasn’t started yet, how do I read it?</em></p><p>If Android crashes or hangs <em>before</em> logd wakes up — or worse, before ADB&#39;s own daemon, adbd, even starts — then both of my windows go dark at once. adb shell dmesg won&#39;t connect. logcat has no narrator to listen to. I&#39;d be standing outside a house with all its lights off, unable to even knock on the door.</p><p>This is where the same old trick from plain Linux came back — the serial console. Except this time, it mattered even more.</p><p>I wired up the same three connections as before:</p><ul><li>Pi’s GPIO 14 (TX) → adapter’s RX</li><li>Pi’s GPIO 15 (RX) → adapter’s TX</li><li>Pi’s GND → adapter’s GND</li><li>The adapter’s own power line — left untouched, since the Pi has its own supply</li></ul><p>And opened the same kind of terminal on my laptop:</p><pre>sudo minicom -s</pre><p>115200 baud, 8 data bits, no parity, one stop bit — the same quiet ritual as before.</p><p>This time, when I powered on the board, I watched something new. First came the bootloader — U-Boot, introducing itself, checking memory, preparing to hand things over. Then the kernel unpacked itself, exactly like it had on plain Linux. And then, right as Android’s own init process took its first breath, I started seeing lines I&#39;d never noticed before — Android&#39;s <em>earliest</em> whispers, happening long before any app, any framework service, or any logcat narrator existed to tell the story properly.</p><p>If something ever went wrong in Android <em>before</em> it could speak through ADB — a driver crashing at the wrong moment, a boot loop that never reached the home screen — this would be the only place left to look. The only light still on, in a house where every other window had gone dark.</p><h3>Same Question, Two Different Houses</h3><p>Looking back at both stories — the plain Linux one, and this Android one — I realized the question never changed. I always just wanted to know: <em>what is my board thinking while it wakes up?</em></p><p>But the answers lived in completely different languages, depending on which operating system I was asking.</p><ul><li><strong>dmesg</strong>, on both systems, is still the kernel&#39;s own private diary — same idea, just reached differently. SSH on plain Linux. adb shell on Android.</li><li><strong>journalctl</strong> on plain Linux becomes <strong>logcat</strong> on Android — both are the fuller story of the whole system, but logcat narrates a much bigger, much louder world of apps and framework services that plain Linux never had to begin with.</li><li><strong>The serial console</strong> stays exactly the same on both — the one window that doesn’t care what operating system you’re running, because it’s watching from a place before any operating system has even introduced itself.</li></ul><p>These days, when I flash a fresh AOSP build onto my Raspberry Pi 5 and it doesn’t come up the way I expect, I don’t panic. I just start opening windows, one at a time — adb shell dmesg first, logcat next, and if both stay silent, I already know exactly where the last light is still burning.</p><p><em>If you enjoyed this, I write about Android AOSP, embedded Linux, and hardware-software internals over at SiliconToSystem — where hardware meets the OS. Follow along as I document my journey from Android app development into kernel and platform engineering.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce307f495e55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wanted to See What My Raspberry Pi Was Thinking While It Woke Up]]></title>
            <link>https://medium.com/@aruncse2k20/i-wanted-to-see-what-my-raspberry-pi-was-thinking-while-it-woke-up-c0e06c0099dc?source=rss-61b50b5088a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0e06c0099dc</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[linux-commands]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <dc:creator><![CDATA[Arun Aditya]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 19:38:28 GMT</pubDate>
            <atom:updated>2026-07-18T19:38:28.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmXFxK-tqs5HApxQmUyZzA.png" /></figure><h3>A story about chasing boot logs, one method at a time</h3><p>There’s a strange moment every time you power on a computer.</p><p>Somewhere between pressing the power button and seeing the login screen, a hundred small things happen — hardware gets detected, drivers load, services start, and the whole system quietly decides “yes, I’m ready now.”</p><p>Most of the time, we never see any of it. We just wait for the screen to load, and we get on with our day.</p><p>But one afternoon, I found myself needing to <em>see</em> that hidden moment.</p><p>I was working with kernel modules on my Raspberry Pi 5 — the kind of work where a driver might misbehave, a device might not get detected, or something might silently fail before I even get a chance to log in. I needed a window into what my Pi was doing <em>while it woke up</em>, not after.</p><p>So I went looking for that window. And I found not one, but three very different ones — each showing me a different slice of the same story.</p><h3>Window One: dmesg — The Kernel&#39;s Own Diary</h3><p>The first thing I tried was the simplest.</p><p>I SSH’d into my Pi:</p><pre>ssh arun@raspberrypi.local</pre><p>And typed one word:</p><pre>dmesg</pre><p>Suddenly, a wall of text scrolled past me — messages about my USB ports being detected, my storage device being recognized, memory being initialized, and further down, even the little kernel module I had built earlier that same week.</p><p>I realized dmesg is like a <strong>diary the kernel keeps for itself</strong>. Every time something happens at the hardware or driver level — a device connects, a module loads, a warning gets raised — the kernel jots it down in this diary, called the <em>kernel ring buffer</em>.</p><p>I wanted timestamps that made sense to a human, not just raw numbers, so I added a flag:</p><pre>dmesg -T</pre><p>And when I was actively testing a kernel module and wanted to watch the diary being written <em>live</em>, I used:</p><pre>dmesg -w</pre><p>I’d open one terminal running dmesg -w, and in another terminal, I&#39;d load my module:</p><pre>sudo insmod hello.ko</pre><p>And right there, in real time, I’d watch my own module’s message appear in the diary. It felt like reading someone’s thoughts as they were being written.</p><p>But I quickly noticed something. This diary only remembers the <strong>current chapter</strong> — the moment the Pi restarts, the diary starts fresh. And it only writes about the <em>kernel</em> — not about the small army of background services that also wake up during boot.</p><p>I needed a bigger book.</p><h3>Window Two: journalctl — The Full Story of the Boot</h3><p>That bigger book turned out to be journalctl.</p><p>Where dmesg only tells the kernel&#39;s side of the story, journalctl tells the <strong>whole system&#39;s story</strong> — the kernel, plus every service that starts afterward: networking coming up, Bluetooth initializing, SSH itself starting (the very thing I used to connect in the first place).</p><p>I typed:</p><pre>journalctl -b</pre><p>The -b means <em>&quot;since the last boot&quot;</em> — and the output was like reading a full transcript of everything that happened, from the very first kernel message to the last service settling into place.</p><p>What surprised me was that this book doesn’t throw away old chapters. I could look at <em>previous</em> boots too:</p><pre>journalctl --list-boots</pre><p>This showed me a list, almost like a table of contents — Boot 0 (the current one), Boot -1 (the one before), and so on. I could open any of them:</p><pre>journalctl -b -1</pre><p>And there it was — a boot from days ago, fully preserved, as if the Pi remembered everything it had ever done.</p><p>One evening, curious to see this happen live, I rebooted the Pi and reconnected the moment it came back online:</p><pre>sudo reboot<br>ssh arun@raspberrypi.local<br>journalctl -b -f</pre><p>Watching it scroll in real time felt oddly satisfying — like watching a machine take its first breath, one line at a time.</p><p>But even this book had a limit. Both dmesg and journalctl need one thing to exist before they can help you: <strong>a working network connection over SSH</strong>. If the Pi never gets that far — if it hangs before Wi-Fi comes up, or crashes before SSH even starts — these two windows go completely dark. You&#39;d be locked out of the very story you&#39;re trying to read.</p><p>That’s when I learned about the third window. The oldest, and in some ways, the most honest one.</p><h3>Window Three: The Serial Console — Watching From Before the Beginning</h3><p>I remember thinking, <em>“If the Pi can’t even boot far enough to let me SSH in, how would I ever know what went wrong?”</em></p><p>The answer was surprisingly old-school: a small USB-to-TTL adapter, and three wires.</p><p>Unlike dmesg and journalctl, which live <em>inside</em> the operating system, the serial console works completely outside it. It doesn&#39;t care if Wi-Fi is up, if SSH has started, or if the operating system has even finished loading. It simply listens to a tiny stream of text the Pi sends out through a physical pin, starting from the very first moment power is applied — even before the bootloader hands control to the kernel.</p><p>I wired it up carefully:</p><ul><li>Pi’s GPIO 14 (TX) → adapter’s RX</li><li>Pi’s GPIO 15 (RX) → adapter’s TX</li><li>Pi’s GND → adapter’s GND</li><li>The adapter’s own power pin — left disconnected, since the Pi has its own power supply</li></ul><p>Then, on my laptop, I opened a serial terminal:</p><pre>sudo minicom -s</pre><p>I set it to 115200 baud, 8 data bits, no parity, 1 stop bit — a combination so common in embedded work that it’s practically folklore at this point.</p><p>And then I powered on the Pi.</p><p>What I saw was the earliest chapter of the whole story — one that dmesg and journalctl never get to tell, because it happens <em>before</em> they even exist. Bootloader messages. Memory checks. The kernel unpacking itself. All of it, scrolling past, long before any login prompt or network connection was even possible.</p><p>It felt like standing at the very beginning of the story, watching the first sentence being written.</p><h3>Three Windows, Three Moments in Time</h3><p>Looking back, I realized each method wasn’t competing with the others — they were simply looking at different moments of the same event.</p><ul><li><strong>dmesg</strong> shows me the kernel&#39;s own private notes, but only for the current session.</li><li><strong>journalctl</strong> shows me the full system&#39;s story, kernel and services together, and even lets me revisit old boots.</li><li><strong>The serial console</strong> shows me everything — even the parts that happen before the operating system itself is fully alive — but it needs physical wires and a bit of old-fashioned patience.</li></ul><p>For most of my day-to-day work, I still just reach for dmesg or journalctl over SSH — quick, no extra hardware, good enough for 90% of what I need.</p><p>But now I keep that little USB-to-TTL adapter close by. Because someday, when a kernel module I write causes something to go wrong <em>before</em> the Pi even gets a chance to say hello over the network, that adapter will be the only window still open — the only way to see what my Pi was thinking in that very first, very fragile moment of waking up.</p><p><em>If you enjoyed this, I write about Android AOSP, embedded Linux, and hardware-software internals over at SiliconToSystem — where hardware meets the OS. Follow along as I document my journey from Android app development into kernel and platform engineering.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0e06c0099dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>