Slashdot is powered by your submissions, so send in your scoop

 



Forgot your password?
typodupeerror
×
Programming Linux

Become a Linux Kernel Hacker and Write Your Own Module 143

M-Saunders (706738) writes "It might sound daunting, but kernel hacking isn't a mysterious black art reserved for the geekiest of programmers. With a bit of background knowledge, anyone with a grounding in C can implement a new kernel module and understand how the kernel works internally. Linux Voice explains how to write a module that creates a new device node, /dev/reverse, that reverses a string when it's written to it. Sure, it's not the most practical example in the world, but it's a good starting point for your own projects, and gives you an insight into how it all fits together."
This discussion has been archived. No new comments can be posted.

Become a Linux Kernel Hacker and Write Your Own Module

Comments Filter:
  • Oh no! (Score:5, Funny)

    by fizzer06 ( 1500649 ) on Tuesday May 27, 2014 @04:53PM (#47102503)
    Just to have Linus publicly cuss me out? No thanks!
    • by Anonymous Coward on Tuesday May 27, 2014 @05:05PM (#47102599)

      you are 100% required to send all your code to linus, even your test builds

      • Comment removed based on user account deletion
        • by xvan ( 2935999 )

          Do you pine for the nice days of minix-1.1, when men were men and wrote their own device drivers?

          Allways sounded like a hacking invitation to me.

    • Take it a badge of honour.

    • by wjcofkc ( 964165 )
      I've been following the Enlightenment project since its inception. A few months ago I had to hop on their mailing list and ask a question for the first time. Rasterman replied, which itself seemed an honor. Doubly so that he kinda called me an idiot in that round about way he does. It was a good day.
      • by Anonymous Coward

        Hopefully your question was "why is enlightenment so horrible after all these years?"

        • by wjcofkc ( 964165 )
          It's not horrible, it's............ misunderstood. : P

          Seriously though, I could write several thousand words on why I love Enlightenment. I've been using Linux since 1996 and right now I am running the Bodhi beta and it's the best experience I've ever had with a DE. Keep in mind, development stalled for over a decade and only recently restarted. Enlightenment is now being developed at breakneck pace and they have some really cool stuff going on. Although I personally can't imagine going with anything less,
  • Very true... (Score:5, Interesting)

    by MindPrison ( 864299 ) on Tuesday May 27, 2014 @04:58PM (#47102547) Journal
    ...I remember my first meeting with Slackware, it was a Linux distro that provoked any user to learn stuff from scratch, and you HAD to use the command line (bash/shell) to install it if you wanted to use it. This forced me to learn Linux. (At least some of the basics)

    It also came with a Kernel compilation system + all the needed libraries and packages, so compiling to your own computer was a few commands and worked right out of the box. And then my curiosity got piqued and this drove me to go into the configuration and find out how I could optimize my kernel to fit my needs. In the beginning it was a lot of trial and error, and it looked real daunting, but after a few tries - it wasn't nearly as scary. Before you knew it, I was coding my first stuff in C++. A lot of fun, actually.

    So yeah, by all means - if you guys have the time, the curiosity, do go ahead and code something, but do yourself a favor - start off easy.
    • Soft spot in my heart for Slack, too -- although I started off with an old RedHat CD I picked up at a garage sale (2.0 kernel series, I think), Slack was the first distro I really started using. Great stuff, though I've now moved on to Debian.

      As to the "start off easy" sentiment, I would highly recommend Project Euler: http://projecteuler.net/proble... [projecteuler.net] fun little programming exercises, and can really be done in any language.
  • Umm (Score:5, Insightful)

    by ADRA ( 37398 ) on Tuesday May 27, 2014 @05:01PM (#47102567)

    Well yes, any C developer (already a minority in the umbrella of 'programmers' these days) can write code for the kernel, but just because one can write software for the kernel doesn't mean they can write anything meaningful to be done in kernel space vs. anywhere else. If you're expecting a slew of new driver hackers reverse engineering chipsets, and implementing better drivers, testing all corner cases (because dev's LOVE testing) I think you're barking up a very small tree, but all the luck to you, becase what's good for Linux is good for me, you, us all.

    • Some of us build hardware and need to write device drivers.
      Cutting through the cruft is exceedingly useful to those of us that want to get the device to work.

    • I've developed Windows drivers before and can say that while yes, it is just plain C or a subset of C++, the APIs are entirely new and come with various curveballs user-mode devs will not have ever dealt with like keeping track of what IRQ level you're at.

      A simple driver is... well, fairly simple. Once you try to do anything interesting though, there's a lot to learn before you can be useful. I'm curious if Linux is any different.

      • by Richy_T ( 111409 )

        The nice thing is, unless you are doing something totally off the wall, there is a good chance that there is already a module out there that does something similar to what you want to do and the open source love is revealed to you. This applies to many other open-source OSs as well, of course.

        Try this with windows and there's a good chance you'll find some incomplete example code from three API revisions ago that won't even compile with the latest libraries (BTDT)

        • Try this with windows and there's a good chance you'll find some incomplete example code from three API revisions ago that won't even compile with the latest libraries (BTDT)

          Uhhhhh.... for the most part, the kernel API in Windows has been remarkably stable. I have an *extremely* non-trivial Windows driver that works from NT all the way through Win 8. The only major disruption in the 10+ years between NT4 and Vista was the TDI client debacle where they deprecated TDI and there were some workarounds that needed to be implemented to run on the new kernel.

          That. Was. All.

          I'm not a Linux kernel dev (though have lots of user-mode Linux/Unix experience), but my understanding

          • I'm not a Linux kernel dev (though have lots of user-mode Linux/Unix experience), but my understanding of that world is "we'll change anything and everything if and whenever we feel like it, and it's up to the rest of the world to keep up with those changes". So your example, ironically, would apply much more to a Linux driver sample than it would a Windows driver sample.

            Linux will change their ABI if necesary, or interal APIs, but not external APIs.

          • by Richy_T ( 111409 )

            I think my specific example was VFW. I was several hours into trying to understand some of the inner workings before finding out they've moved to some new flavor of the week. I threw in the towel at that point as I was only monkeying around with an idea.

    • If you're expecting a slew of new driver hackers reverse engineering chipsets, and implementing better drivers, testing all corner cases (because dev's LOVE testing) I think you're barking up a very small tree

      Don't be silly.

      The goal is to get a nifty new string manipulation API implemented in kernel space. Imagine how slick it would be to use (error checking omitted for brevity):

      char* buf; FILE* fp = fopen("/dev/strcat", "r+");
      fwrite(string1, string1_length, 1, fp);
      fwrite(string2, string2_length, 1, fp);
      fflush(fp);
      buf = malloc(string1_length + string2_length);
      fread(buf, string1_length + string2_length, fp);
      fclose(fp);

      I mean, how awesome is that? Only 8 lines of code to concatenate two strings! It

    • C developer: already a minority in the umbrella of 'programmers' these days

      - I write in Java because I have to.
      - I write in PHP because I choose to.
      - I write in C because I can
      (originally was Windows/Mac/Linux)

  • by nblender ( 741424 ) on Tuesday May 27, 2014 @05:03PM (#47102575)

    In kernel space, no one can hear you scream.

  • I sent it Pi and the universe imploded. Fortunately we had recent back-ups. Though the ones from after Jeb Bush* became president went *ahem* mysteriously missing.

    *Replace with Hillary Clinton if you're on the other team.

  • Become a Linux Kernel Hacker and Write Your Own Module

    I don't want to. You do it. sudo you do it.

    • by Anonymous Coward

      You only sudo do that if you have only dollar no hash. You need to exchange the dollar for #. Then smoke the prompt while entering you command into the wonder buffer. Then see how magically the penguin box obeys even your dd-if=/dev/zero-of=/dev/sda-iest wishes.

      sudo should be called SINU - sudo is not unix. Not evrey distro dealer can offer you rial pure sudo. Only use pure sudo! {Hard,Soft}links can harm you health!

      To get really high even hash (#) is not enough, your'e really need to enter your kernel spac

    • I don't want to. You do it. sudo you do it.

      Exactly. Why would I do anything when we have the open source community that will do it for me?

  • This item hit reddit earlier, so I'll repeat my advice.

    It might be easier to begin with a kernel module that is useful to you, and either work with the developer or find a module where the developer has lost interest instead.

    I worked on two kernel modules, one called oplbeep and the other was totem. Both very simple things that required porting when interfaces changed. Today I work on the vmware modules which are always requiring tweaking (at least unless you upgrade to the latest version of VMWare more reg

  • From the tutorial:
    ----
    static struct buffer *buffer_alloc(unsigned long size)
    {
    struct buffer *buf;
    buf = kzalloc(sizeof(*buf), GFP_KERNEL);
    if (unlikely(!buf))
    goto out;
    ----
    I haven't seen a tutorial written where "goto" was recommended...ever. When I was taught C back in the late 20th century, we weren't taught how to use goto or when. Now that I'm older and wiser, the

    • by Anonymous Coward

      The goto statement comes in handy when a function exits from multiple
      locations and some common work such as cleanup has to be done. If there is no
      cleanup needed then just return directly.

      The rationale is:

      - unconditional statements are easier to understand and follow
      - nesting is reduced
      - errors by not updating individual exit points when making
      modifications are prevented
      - saves the compiler work to optimize redundant code away ;)

      https://www.kernel.org/doc/Documentation/CodingSty

    • by frank_adrian314159 ( 469671 ) on Tuesday May 27, 2014 @08:12PM (#47103651) Homepage

      Just like any other construct - when it makes the code more clean, clear, correct, and/or optimized. These are tradeoffs.

      For instance, let's say you have a function having a deeply nested conditional:

      if (!a) {
          if (!b) {
              if (!c) {
      ...

      } } }

      This code might be more simply understood as:

      if (a) goto done;
      if (b) goto done;
      if (c) goto done;
      ...
      done:
      ...

      • Or you could decompose it like an actual software engineer, getting readability and testability and avoiding goto into the bargain:

        bool a() { ... }
        bool b() { ... }
        bool c() { ... }

        void thing()
        {
            a && b && c;
        }

        My C syntax is a bit rusty, but you get the idea. GCC will likely inline them if they are small anyhow, so you probably won't suffer functional call overhead.

        • If you think your example was more readable than the parent, I don't think you're entirely clear on what the word "readable" actually means.

          Go home = Very Readable
          Go to the Store = Readable
          Go to 713 Bond Street = Readable
          goto label = Readable

          void thing() { a && b && c; } = NOT READABLE!

          The idea behind what very experienced programmers call "readability" is to reduce the highly domain-specific knowledge that the reader must study before comprehending your code. The more expertise required in

      • by tkotz ( 3646593 )

        I like that you had to do a logic inversion to make your point. You are really showing how confusing inverted logic can be. The if-else code equivalent to your goto code is:

        if (a) { // Done - or log error A
        }
        else if (b) { // Done - or log error B
        }
        else if (c) { // Done - or log error C
        }
        else
        { ...
        }

        or it could be written more succinctly as:

        if( !( a || b || c) ) { ...
        }

    • by shoor ( 33382 )

      I got my intro to programming in the mid 1960s with 'the college computer' a PDP-8 that we programmed in Fortran using punched cards. In those days, just getting access to a computer was a pretty big deal, but things were changing, so 'programming paradigms' started appearing, and the first one that I remember was 'structured programming'. This is where I first heard the mantra of 'goto-less' programming. (Before that, the mantra was not to write self-modifying code, which was something you almost had to

    • by c ( 8461 )

      Any wise old vets want to chime in about when to use "goto" and when not to?

      Not claiming to be a wise old vet, but as a general rule of thumb, the ideal way to use it is to emulate control structures from even higher level languages. For example, if in C++ you'd write an error handling behavior in a function as an exception, in C you might goto a common area to cleanup transient memory and gracefully return an error code. Which is exactly what that snippet you've shown is doing.

  • by Eravnrekaree ( 467752 ) on Tuesday May 27, 2014 @07:25PM (#47103379)

    While the article shows a cute little example on how to write a useless module, it does not show anyone how to actually write a serious kernel module. The Linux kernel has never been known for documenting kernel internals, such documentation is scant at best and simply not sufficient to write a module. It is safe to say tha due to the poor practices of Kernel developers who constitently ignore good practice by not Documenting Their Crap, the kernel is an elite club of developers with knowledge that is secret. The practices of the Linux kernel development is just sheer sloppiness, horribly bad practice. They could have easily set up a Wiki and documented the interfaces and their architecture. What we see with the kernel developers is that they do not care about anyone else, not users, and not even outside techies, so why would they care about whether or not an outsider can understand the kernel, just as why would they care if a user can upgrade kernel versions without having all of their device drivers blow up. As anyone well versed in computer science knows, computer code is rarely self documenting, especially the kernel, and trying to reverse document a large software project is an outrageous waste of time and can be enough of a problem that it keeps even seasoned programmers away from the project. A huge piece of undocumented code is just not worth the effort to learn.

    • To be honest - I expected the example to be the programmer's equivalent of a guitarist playing Stairway to Heaven. I'm actually disappointed the example wasn't a kernel module to print "Hello World"! :)
    • And none of the article is new. There have been examples of simple modules for linux kernels ever since modules were implemented, in print and on the web. What's new about this, except that Slashdot is now an advertiser for blog articles?

  • ... any competent Unix admin could write a device driver. Now a days they barely know the grep.
  • by Tyler Durden ( 136036 ) on Tuesday May 27, 2014 @08:26PM (#47103761)

    You know, I'd like to think there was a time when the majority of Slashdot users could cheerfully take on writing modules for the Linux kernel or *gasp* just code in C.

    • by jythie ( 914043 )
      There was never such a time. Slashdot has always had a pretty good variety of tech people, so for some it would be daunting, some it would not, depending on how close it was to their own domain knowledge.
    • Depends what you mean by "code in C"

      I think the vast majority of us at some point have made a C program go "Hello World!" Many more of us have overloaded some operators and learned some other elements of the language.

      But there's a world of difference between that, and being a competent C developer. That is something that takes years to learn and quite a bit of work. And while I am sure if I had the time and the yearning to be one I could, I just know I am not.

      • by Buzer ( 809214 )
        Many more of us have overloaded some operators and learned some other elements of the language.

        Doesn't sound a very good idea to do in C... Sure, you can always #define +, but don't wonder why all of your coworkers will hate you for it.

        • LOL... You might want to read my post.

          Having taken some programming courses that covered C, I've created a pointer or two and overloaded a few operators, but you really wouldn't want to let me become a developer on any major C based project.

          (although that doesn't mean I don't think I COULD be one if I put in the time or effort -- just that familiarity with a language and the ability to write kernel drivers are two very different things)

    • You know, I'd like to think there was a time when the majority of Slashdot users could cheerfully take on writing modules for the Linux kernel or *gasp* just code in C.

      I suggest that most people here are just consumers. They try various distros and use open source code that has been readily made available for them. They rarely look at the code or even make the smallest modifications. Not to even talk about something like writing kernel modules from scratch. On the other hand, I believe that the UNIX command line skills of people here are generally quite good, and thus they can drill quite deep in user space administration, configuration, automation and proper bug reportin

  • When will people give up this love affair with the systemd/NetworkManager/udev/automagic crap? What makes Linux kickass is how NOT Windows-like it is.

    • by Anonymous Coward

      I'm going to write a kernel module called /dev/registryd that implements a registry because doing string handling in the kernel is a good thing.

  • by Anonymous Coward on Tuesday May 27, 2014 @09:53PM (#47104289)

    Take that APK! I'm going to put my motherfucking hosts file in the kernel..that's right.. I'm going to have a /dev/hosts

    You heard me right! /dev/motherfucking/hosts

    True ring 0 baby!

  • by riffraff ( 894 ) on Wednesday May 28, 2014 @09:05AM (#47107419) Homepage

    I once had to write a module for a pc/104 board on an embedded system running kernel 2.4. It had 8 relays that were write-only, there was no way to query a relay for what it's current position was, so I kept track of it myself and made the cached status available by a proc entry.

    It wasn't really that hard and I learned a bit more about how the kernel modules got initialized and executed. I wrote a couple of others also, like for the Sensoray Model 518 (which is discontinued now I think).

Our OS who art in CPU, UNIX be thy name. Thy programs run, thy syscalls done, In kernel as it is in user!

Working...