Slashdot Mirror


Become a Linux Kernel Hacker and Write Your Own Module

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."

143 comments

  1. Oh no! by fizzer06 · · Score: 5, Funny

    Just to have Linus publicly cuss me out? No thanks!

    1. Re:Oh no! by TechyImmigrant · · Score: 1

      Take it a badge of honour.

      --
      I should use this sig to advertise my book ISBN-13 : 978-1501515132.
    2. Re:Oh no! by wjcofkc · · Score: 2

      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.

      --
      Brought to you by Carl's Junior.
    3. Re:Oh no! by Anonymous Coward · · Score: 1

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

    4. Re:Oh no! by wjcofkc · · Score: 2

      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, at the end of the day I advise most people to use something else like.... elementary OS. The fact is Enlightenment is simply to complicated for most people to bother with the learning curve.

      --
      Brought to you by Carl's Junior.
    5. Re:Oh no! by Anonymous Coward · · Score: 0

      Enlightenment is a nice WM, but it has one killer problem for me: the difficulty of configuring it. Seriously, there are at least three different ways to get to the same menu, but the menus mostly just repeat themselves. You can find all sorts of options on how to get it to change themes and icons, but I couldn't get it to place certain applications on certain desktops when they are started. The graphics are very pretty, but the theme selection is pretty limited (I've been trying to find a nice repository, but most I go to either don't have working themes, or have long since been shutdown). However, if they're rapidly developing it, I think I'll take another look at it. Maybe something's changed in the last year. Currently, I use the i3 window manager, for its awesome (hehe, pun most certainly intended) tiling capabilities, ease of configuration, and great multimonitor support.

  2. Very true... by MindPrison · · Score: 4, Interesting

    ...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.

    --
    What this world is coming to - is for you and me to decide.
    1. Re:Very true... by by+(1706743) · · Score: 1

      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... fun little programming exercises, and can really be done in any language.

    2. Re:Very true... by inasity_rules · · Score: 2

      A Project Euler kernel module would be an interesting way to solve some of those...

      --
      I have determined that my sig is indeterminate.
  3. Been there done that... by Anonymous Coward · · Score: 0

    ... ten years ago, interesting exercise for the teachers, not sure the students liked it though except for the 1% ubergeeks.

    1. Re:Been there done that... by Verdatum · · Score: 2

      I feel like any OS course worth a damn should force you to write at least one OS kernel module; and unless your course uses one of the academic OSes, it might as well be on Linux.

    2. Re:Been there done that... by Anonymous Coward · · Score: 1

      That was my point when I designed this course, I'm not sure I would have the energy and the will to do that again, and I'm only 35.
      Give me another ten years and I'll teach VB...

    3. Re:Been there done that... by Mordok-DestroyerOfWo · · Score: 1

      Give me another ten years and I'll teach VB...

      And in 20 more you'll be teaching macros in Filemaker. But I've heard that the lobotomy required for either skillset is rather painless.

      --
      "Never let your sense of morals prevent you from doing what is right" - Salvor Hardin
    4. Re:Been there done that... by stjobe · · Score: 1

      Are you me from 2004?

      Ten years ago I taught my sysadmin students how to write kernel modules in Linux (on their LFS systems I had them build); these days I make a living coding in C#...

      Also, in 2004 I was 35...

      --
      "Total destruction the only solution" - Bob Marley
  4. Umm by ADRA · · Score: 4, Insightful

    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.

    --
    Bye!
    1. Re:Umm by TechyImmigrant · · Score: 2

      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 should use this sig to advertise my book ISBN-13 : 978-1501515132.
    2. Re:Umm by Anonymous Coward · · Score: 0

      Good kernel developers have a number of options. For example, dealing with Android devices. If one can get the specs for SoC functions, there might be functionality on a tablet or smartphone just waiting to be taken advantage of by someone who can read the details and write a kernel module to take advantage of this.

      Disclaimer: More kernel developers and fewer people making yet another fleshlight app on iOS or Android is a good thing. It takes real talent to program on this level due to resource limitations and the fact that one goof, and the bug is a show-stopper.

    3. Re:Umm by PhrostyMcByte · · Score: 2

      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.

    4. Re:Umm by DrPBacon1294 · · Score: 0

      Well, the embedded systems market is due to flourish any minute now. There will likely be many small trees worth barking up. Arch on Rockchip!

    5. Re:Umm by Richy_T · · Score: 2

      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)

    6. Re:Umm by koreanbabykilla · · Score: 1

      "Fleshlight app" lolol. Did you mean to do that?

    7. Re:Umm by Anonymous Coward · · Score: 0

      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.

      An old rule of thumb: compilers are 10x tricker to write than applications, OS-level code is 10x trickier than that.

      I don't know about the compiler factor anymore, since modern GUI programs tend to be pretty complex themselves, but the problem with OS-level code is that concurrency is rampant plus you have to be aware of hardware state.

    8. Re:Umm by swillden · · Score: 2

      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 would even be trivial to include multiple copies of string1 and/or string2 if you wanted!

      And since it's implemented in the kernel you know it'll be uber fast and secure.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    9. Re:Umm by Mordok-DestroyerOfWo · · Score: 1

      "Fleshlight app" lolol. Did you mean to do that?

      Now that's an Android app that would give iOS a run for its money.

      --
      "Never let your sense of morals prevent you from doing what is right" - Salvor Hardin
    10. Re:Umm by fizzer06 · · Score: 1

      What happened to all of the really good fart apps?

    11. Re:Umm by WalrusSlayer · · Score: 2

      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 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.

    12. Re:Umm by hobarrera · · Score: 2

      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.

    13. Re:Umm by Anonymous Coward · · Score: 0

      Linux changes kernel APIs all over the place. It doesn't change user space things and system calls and similar.

      I worked for a shop which had a set of high-performance PCIe drivers. Windows WDM-model drivers worked everywhere from NT to Windows 8 without any changes.

      The Linux drivers on the other hand, had hundreds of #ifdef's against kernel versions everywhere. It seems that every 3 or 4 versions there was some symbol name change and/or semantic difference related to something critically important like interrupts.

      When Linux people say they don't break the interface - they are only referring to user-space stuff. The kernel is all about optimization and forward-thinking. They do not care about backwards compatibility.

    14. Re:Umm by Anonymous Coward · · Score: 0

      and if you had submitted those for inclusion into the kernel, all those changes would have been done for you by those who proposed the change - even without any ifdef'ery.

    15. Re:Umm by putaro · · Score: 1

      But not every driver gets included into the kernel. I wanted to use an open source ISDN driver and it was broken because some yahoo had decided that the kernel logging macros all needed to be renamed.

      I did kernel development back before Linus even started on Linux and I avoid Linux internals like the plague because they're in a constant state of flux.

    16. Re:Umm by putaro · · Score: 1

      In my experience the concurrency will get you but it's also the lack of memory protection that will drive you nuts. The Linux kernel has everything running in the same address space so a bug in some dippy USB driver can crash the whole system. And that is why you shouldn't let n00bs write kernel code.

    17. Re:Umm by hcs_$reboot · · Score: 1

      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)

      --
      Slashdot, fix the reply notifications... You won't get away with it...
    18. Re:Umm by Alioth · · Score: 1

      That's probably a feature not a defect if it discourages people from writing kernel code which doesn't need to be kernel code (for example drivers for USB devices).

    19. Re:Umm by Alioth · · Score: 1

      This is why USB drivers should be in userspace (libusb).

    20. Re:Umm by Richy_T · · Score: 1

      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.

    21. Re:Umm by hobarrera · · Score: 1

      Why was your driver maintained out-of-tree?

  5. Yay by Anonymous Coward · · Score: 0

    You too can modify the kernel with a module that has only been tried on one computer with only the bit of functionality you want.

  6. just remember ... by nblender · · Score: 5, Funny

    In kernel space, no one can hear you scream.

    1. Re:just remember ... by Anonymous Coward · · Score: 1

      In kernel space, no one can hear you scream.

      Not until you write your own scream driver.

    2. Re:just remember ... by Anonymous Coward · · Score: 0

      ***********
      KHAN !
      ***********

    3. Re:just remember ... by iggymanz · · Score: 2

      "I have no dev device, and I must scream"

    4. Re:just remember ... by mlts · · Score: 3, Insightful

      There is always the ability to panic.

    5. Re:just remember ... by rabtech · · Score: 1

      Yeah but if you get mad and start throwing things you can end all of existence. Some say the universe would collapse and reboot but sounds like hocus-pocus to me!

      --
      Natural != (nontoxic || beneficial)
  7. ATTENTION, like EVERYBODY by Anonymous Coward · · Score: 0

    If you are going to do this, seriously have your code reviewed by all the available static analyzers you can get your hands on. Double check all your buffer lengths with a calculator. Read a book on C security vulnerabilities.

    In a kernel module, you know small C coding defects can catapult into serious problems because the kernel will execute your code with superuser authority.

    1. Re:ATTENTION, like EVERYBODY by Anonymous Coward · · Score: 0

      Or don't run your alpha quality modded kernel on a public box?

  8. just because by Anonymous Coward · · Score: 5, Funny

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

    1. Re:just because by Anonymous Coward · · Score: 3, Funny

      No it was simply a joke Admiral Aspergers.

    2. Re:just because by Jeremiah+Cornelius · · Score: 0

      Will this proposed kernel module auto-genrate Edward Snowden stories for the Slashdot frontpage, with a POST through the kHTTPd?

      Will these stories swap links with OTHER stories on the Slashdot frontpage?

      What about Firehose?

      --
      "Flyin' in just a sweet place,
      Never been known to fail..."
    3. Re:just because by binarylarry · · Score: 1

      libsnowden is on hold because the author was detained by the NSA.

      --
      Mod me down, my New Earth Global Warmingist friends!
    4. Re:just because by drolli · · Score: 1

      And you actually have to share it only with the person you are giving the binary to.

    5. Re:just because by Anonymous Coward · · Score: 0

      libsnowden is on hold because the author was detained by the NSA.

      But /dev/coldfjiord is OK.

    6. Re:just because by RightwingNutjob · · Score: 1

      Ah! So Captain Obvious finally has someone to report to! It's all falling into place...but where does Major Pain fit into the picture?

    7. Re:just because by stjobe · · Score: 1

      where does Major Pain fit into the picture?

      He's in another chain of command, he reports to General Mayhem.

      --
      "Total destruction the only solution" - Bob Marley
    8. Re:just because by Anonymous Coward · · Score: 0

      Actually General Disarray, who in turn is the lackey of Professor Chaos....

    9. Re:just because by Jeremiah+Cornelius · · Score: 1

      libsnowden is on hold because the author was detained by the NSA.

      I think they just want to loosen his algorithm and get him to drop his entropy.

      --
      "Flyin' in just a sweet place,
      Never been known to fail..."
    10. Re:just because by Anonymous Coward · · Score: 0

      BTW: NSA fags reading this, wipe the shit off the end of your dicks, before jabbing at the keyboards, OK?

    11. Re:just because by Anonymous Coward · · Score: 0

      That language only applies if you don't give the source with the binary. If you give the source to the person to whom you gave the binary, your obligation is done.

      Now, if that person gives out the binary, they THEY have to pass along the source or accompany it with a written offer...

    12. Re:just because by Anonymous Coward · · Score: 0

      To quote the FSF:

      If you choose to provide source through a written offer, then anybody who requests the source from you is entitled to receive it.

      The reason we require the offer to be valid for any third party is so that people who receive the binaries indirectly in that way can order the source code from you.

      http://www.gnu.org/licenses/gp...

    13. Re:just because by Anonymous Coward · · Score: 0

      Idiot troll post. What a moron.

    14. Re:just because by devman · · Score: 1

      If you commercially distribute binaries not accompanied with source code, the GPL says you must provide a written offer to distribute the source code later. When users non-commercially redistribute the binaries they received from you, they must pass along a copy of this written offer. This means that people who did not get the binaries directly from you can still receive copies of the source code, along with the written offer.

      You sort of proved the GP's point. Only if you choose to use written offer must the offer be good for any third party. If, instead, one distributes binaries with source, there is no obligation to third parties as they should have received source from their distributor.

    15. Re:just because by spitzak · · Score: 2

      You seem to have not italicized the important portion, even though you cut and pasted it into your post! Here I will do it for you:

      If you commercially distribute binaries not accompanied with source code, the GPL says you must provide a written offer to distribute the source code later. When users non-commercially redistribute the binaries they received from you, they must pass along a copy of this written offer. This means that people who did not get the binaries directly from you can still receive copies of the source code, along with the written offer.

      I think it is your turn to read the italicized portion until it sinks in.

    16. Re:just because by Anonymous Coward · · Score: 0

      Dickbreath???

    17. Re:just because by Anonymous Coward · · Score: 0

      You're missing a comma, Admiral Shittygrammar.

    18. Re:just because by QRDeNameland · · Score: 2

      Don't forget about Colonel Panic!! (to bring this back kinda on-topic)

      --
      Momentarily, the need for the construction of new light will no longer exist.
    19. Re:just because by craigminah · · Score: 2

      Funny they say programming something to the Linux kernel is "hacking" rather than "programming.' Most likely to draw in the l33t kids who want to haxor something.

    20. Re:just because by xvan · · Score: 1

      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.

    21. Re:just because by Anonymous Coward · · Score: 0

      that term has existed for quite awhile, unrelated to haxing

    22. Re:just because by drolli · · Score: 1

      Probably my post was to long to understand for the AC.

    23. Re:just because by HagraBiscuit · · Score: 1

      Aided and abetted by Private Parts, Corporal Punishment and Sergeant Rock.

    24. Re:just because by Anonymous Coward · · Score: 0

      Funny they say programming something to the Linux kernel is "hacking" rather than "programming.' Most likely to draw in the l33t kids who want to haxor something.

      "hacking" got co-opted (similarly to how "gay" refers to persons of homosexual inclination rather than happy people these days. not judging in this comparison, just an example of co-opting). It simply means engineering something in a clever way, the canonical example being a model railway control system being built with phones. There is still a (for lack of a more positive word) stubborn section of the population that refuses to let that term refer to script kiddies, warez/scene types, or other persons who are, to them, "cracking". Google "Hacker Ethic" some time, most results will provide a bit more insight and historical information than I care to get into right now.

  9. Hello World! by Anonymous Coward · · Score: 0

    Searched TFA for "Hello World" ... left satisfied.

  10. call for warranty service by Anonymous Coward · · Score: 2, Funny

    your sense of humor is broken

  11. 1982 all over again and boy am I excited by Anonymous Coward · · Score: 0

    Not really.

    Maybe this is one way to indoctrinate next decade's "We work for free and like it dammit!" generation?

    1. Re:1982 all over again and boy am I excited by Anonymous Coward · · Score: 0

      Really? I wish to subscribe to your newsletter containing listings of free jobs I can work for free.

    2. Re:1982 all over again and boy am I excited by Anonymous Coward · · Score: 0

      A lot of open source is done like this.

  12. Well by Richy_T · · Score: 1

    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.

  13. Stop telling me what to do! I don't want to! by wonkey_monkey · · Score: 2

    Become a Linux Kernel Hacker and Write Your Own Module

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

    --
    systemd is Roko's Basilisk.
    1. Re:Stop telling me what to do! I don't want to! by Anonymous Coward · · Score: 1

      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 space quarters for ring 0 to rulez them all.

    2. Re:Stop telling me what to do! I don't want to! by jones_supa · · Score: 1

      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?

    3. Re:Stop telling me what to do! I don't want to! by RavenLrD20k · · Score: 1

      Research. Learning. Curiosity. World Domination.

  14. hacking by Anonymous Coward · · Score: 0

    I've heard of people hacking into a computer system or a network, but not the kernel. I guess malware can hack into the kernel in order to take over the computer system. I learned something new.

    1. Re:hacking by jones_supa · · Score: 1

      So it has come to this.

    2. Re:hacking by Gallefray · · Score: 1

      I've heard of people hacking into a computer system or a network, but not the kernel. I guess malware can hack into the kernel in order to take over the computer system. I learned something new.

      . . . Have you never read the JARGON file? :0 http://jargon-file.org/archive...

  15. Good! Now I have questions: by Anonymous Coward · · Score: 0

    I want to drive mouse and keyboard directly from the user space (with admin privileges if needed). I.e. bypassing qt, x windows, so that from the other application it will be indistinguishable from user's input (almost). The question is where do I begin?

    PS: Nothing criminal, just software automation.

    1. Re:Good! Now I have questions: by Tough+Love · · Score: 2
      --
      When all you have is a hammer, every problem starts to look like a thumb.
  16. Uberdupe by Anonymous Coward · · Score: 0

    Why has this article from 15 years ago just appeared? Is it another beta bug?

  17. GOTOs by Anonymous Coward · · Score: 0

    When I looked through the code, I initially cringed at the use of GOTOs, not knowing that the Linux kernel uses them extensively.

    Here's a mailing list thread that explains the rationale:
    http://koblents.com/Ches/Links/Month-Mar-2013/20-Using-Goto-in-Linux-Kernel-Code/

    1. Re:GOTOs by tomhath · · Score: 1

      Interesting thread. But it would be nice if Linus would tell us what he really thinks...

    2. Re:GOTOs by NikeHerc · · Score: 1

      rationale

      The koblents.com link is an interesting read and using a goto may actually be valid inside an o.s. Having said that, after having written a significant number of tens of thousands of lines of C (most of which was outside the kernel), I still have never used a goto and I don't plan to.

      --
      Circle the wagons and fire inward. Entropy increases without bounds.
  18. My advice by jgotts · · Score: 1

    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 regularly) but I do that just to get my work done.

    1. Re:My advice by Tough+Love · · Score: 1

      Starting with a dead simple module like this is correct.

      --
      When all you have is a hammer, every problem starts to look like a thumb.
  19. First Tutorial I've seen with Goto... by Prien715 · · Score: 1

    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 instruction has its place -- especially in code where performance is paramount -- but it can also be less confusing than other control structures in the right situation. (I'm still uncomfortable using it myself.)

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

    --
    -- Political fascism requires a Fuhrer.
    1. Re:First Tutorial I've seen with Goto... by Anonymous Coward · · Score: 1

      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/CodingStyle

    2. Re:First Tutorial I've seen with Goto... by Anonymous Coward · · Score: 0

      I'm not old or wise but I do use goto's it's fairly common in kernel code. I've written several drivers in Windows and Linux, and use goto's in plenty of spots, but for a very specific reason, and under a few constraints. The reasons being that there is some staging of setup that is going where you have to do something like:
      { ...
              if(setup1() != SUCCESS)
              {
                      goto undo_setup1;
              } // Depends on setup1 success
              if(setup2() != SUCCESS)
              {
                      goto undo_setup2:
              }

                return SUCCESS;

      undo_setup2:
              cleanup2();
      undo_setup1:
              cleanup1();
              return FAILED;
      }

      This allows you to free and unregister things in the correct order without making failure steps with a lot duplicated calls that amounts to the same thing anyway. So it is very useful for handling error conditions where you need to free allocations that have happened up to a point, unmap some IO, etc.

    3. Re:First Tutorial I've seen with Goto... by frank_adrian314159 · · Score: 3, Informative

      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:
      ...

      --
      That is all.
    4. Re:First Tutorial I've seen with Goto... by shoor · · Score: 2

      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 be writing assembly language code to be able to do, though COBOL had an 'alters' statement as I recall.)

      I remember being somewhat startled by the idea of excluding gotos. How could you write non trivial code without any goto statements? I actually thought of it almost as a challenge to figure out how to do so. The opposite of structured code was 'spaghetti code'. Anyway, it's become a conventional bit of wisdom that I suppose is just automatically passed down to each generation of students without anyone ever seriously questioning it, except those who find they really need it sometimes. At some point I started defiantly putting an occasional goto in my code again, but not often.

      --
      In theory, theory and practice are the same; in practice they're different. (Yogi Berra & A. Einstein)
    5. Re:First Tutorial I've seen with Goto... by c · · Score: 1

      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.

      --
      Log in or piss off.
    6. Re:First Tutorial I've seen with Goto... by Anonymous Coward · · Score: 0

      What PP said: if that illustration of the use of "goto" isn't exception handling in a sheep's clothing, I don't know what is.

    7. Re:First Tutorial I've seen with Goto... by musicmaker · · Score: 1

      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.

      --
      Everyone is living in a personal delusion, just some are more delusional than others.
    8. Re:First Tutorial I've seen with Goto... by tkotz · · Score: 1

      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) ) { ...
      }

  20. Writing modules near impossible by Eravnrekaree · · Score: 3, Interesting

    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.

    1. Re:Writing modules near impossible by Anonymous Coward · · Score: 0

      Sounds like there needs to be an apprenticeship system. Get eager, smart younguns to work side-by-side (virtually) with experienced devs and generate documentation. The kernel gets that code documented and the younguns get deep experience with the internals, plus really juicy resume' bait. That's pretty standard practice in other professions, or used to anyway.

    2. Re:Writing modules near impossible by Darinbob · · Score: 1

      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?

    3. Re:Writing modules near impossible by Anonymous Coward · · Score: 0

      Most of the kernel interfaces that are used by driver writers are very well documented. There are large comments above important structures and functions, as well as a Documentation folder that describes large subsystem. Furthermore, there are numerous books that describe the kernel architecture from different perspectives - just pick the author you think best writes to your learning style.

      The poorly-documented parts tend not to be in the core architecture, but in the fringes. The driver for that network card from 1990? The one that the kernel dev had to write by reverse engineering the hardware because the device wasn't documented? Those instances have poorer documentation (if any), and yet the source code reveals more information than if we had nothing. But if you have a new device for which you wish to write a Linux driver, the interfaces you need are all well-documented, and easier to use than the interfaces in other kernels such as Windows or FreeBSD (I know because I have programmed in all of them).

    4. Re:Writing modules near impossible by Anonymous Coward · · Score: 0

      I'd bet a large amount of us would disagree.
      As a rule of thumb, good code is self-documenting and bad code needs comments.
      Code in kernels (most of them) is usually of high quality, so it often points to a lack of understanding on the part of the reader.

  21. In my day... by dfn5 · · Score: 1

    ... any competent Unix admin could write a device driver. Now a days they barely know the grep.

    --
    -- Thou hast strayed far from the path of the Avatar.
    1. Re:In my day... by Anonymous Coward · · Score: 0

      Riiiiight..

  22. VERY OLD ARTICLE by Anonymous Coward · · Score: 0

    This is a repeat article that was on slashwhore about 6-8 years ago. Nothing new with this crap.

  23. Thanks for the bug. by Anonymous Coward · · Score: 0

    You're fired!

  24. "Daunting" by Tyler+Durden · · Score: 2

    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.

    --
    Happy people make bad consumers.
    1. Re:"Daunting" by Anonymous Coward · · Score: 0

      Learn Rust or Visual Basic.net for thee kernel safety...

    2. Re:"Daunting" by jythie · · Score: 1

      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.

    3. Re:"Daunting" by Tyler+Durden · · Score: 1

      Well then I guess I'll just have to take your word for it Mister 914043. ;)

      --
      Happy people make bad consumers.
    4. Re:"Daunting" by Ummon · · Score: 1

      Take mine too.

    5. Re:"Daunting" by hax4bux · · Score: 0

      And mine. There never was a world of "with many eyeballs, all bugs are shallow"

    6. Re:"Daunting" by ChunderDownunder · · Score: 1

      Example kernel module written in rust, for those interested...

      https://github.com/tsgates/rus...

    7. Re:"Daunting" by KingOfBLASH · · Score: 1

      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.

    8. Re:"Daunting" by Buzer · · Score: 1
      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.

    9. Re:"Daunting" by musicmaker · · Score: 0

      OpenSSL much?

      --
      Everyone is living in a personal delusion, just some are more delusional than others.
    10. Re:"Daunting" by KingOfBLASH · · Score: 1

      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)

    11. Re:"Daunting" by Anonymous Coward · · Score: 0

      woooosh ?

      The parent meant that there is no overload of operator in C, so there is a very low likelihood that you ever "... overloaded a few operators," as you put it. That is a C++ feature. And don't get (Lin)us started on using C++ in the kernel.

    12. Re:"Daunting" by jones_supa · · Score: 2

      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 reporting.

    13. Re:"Daunting" by KingOfBLASH · · Score: 1

      And this is why you should keep me away from any C based kernel development ;)

      Fuzzy memories of what may or may not be and how to do things. And I'd bet other /.s have similar experiences

    14. Re:"Daunting" by Anonymous Coward · · Score: 0

      I think the point is that, strictly speaking, you can't overload functions in C. You can in C++ but C++ isn't C :).

    15. Re:"Daunting" by retchdog · · Score: 1

      and my axe!

      --
      "They were pure niggers." – Noam Chomsky
  25. I got to the part about udev and closed the window by Gothmolly · · Score: 0

    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.

    --
    I want to delete my account but Slashdot doesn't allow it.
  26. Hello World ... by JackCorbae · · Score: 1

    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"! :)

  27. screw it i'm gonna put my hosts file in the kernel by Anonymous Coward · · Score: 4, Insightful

    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!

  28. Also uinput, /dev/input/mice, use the damn API by raymorris · · Score: 2

    > PS: Nothing criminal, just software automation.

    The GUI probably calls function in a library, if not command line binaries. You are normallybetter off using the library directly rather than emulating GUI input from the user.

    To fake user input, see uinput. Also, you can capture the events using od tool from the /dev/input/mice and then replay them once you have decoded the sequence.

    # cat /dev/input/mice | od -t x1 -w3
    0000000 08 02 00
    0000003 08 08 00
    0000006 08 09 00
    0000011 08 07 00
    0000014 08 04 00
    0000017 08 01 01
    0000022 08 00 02
    0000025 08 02 02

    1. Re:Also uinput, /dev/input/mice, use the damn API by trev.norris · · Score: 1

      That trick is pretty slick.

      As one of what I feel to be a growing breed of Linux users that started off in Ubuntu, and has very very slowly been learning how Linux works internally, all of this is still a bit of black magic. Is there a "From Ubuntu to Linux Hacker" guide out there that briefly and simply explains how the Linux kernel works? All the resources I've found get too deep too quickly.

  29. And "Hello, World" means you can write C! by Anonymous Coward · · Score: 0

    I think not

  30. Re:I got to the part about udev and closed the win by Anonymous Coward · · Score: 1

    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.

  31. device driver by riffraff · · Score: 2

    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).

  32. /dev and /proc. See http://www.tldp.org/, experts by raymorris · · Score: 1

    You might find The Linux Documentation Project handy. You don't need to know anything about kernel internals to use /dev/input/mice or any of the other devices represented in the /dev filesystem, though. All of the hardware devices in the system can be read and written from /dev , which also includes some pseudo devices such as /dev/random and /dev/null . See:

    http://www.tldp.org/LDP/Linux-...

    In fact, I'm a full time programmer and sysadmin using Linux exclusively, and I've had exactly ONE case where I needed to look at kernel code. That's my one credit in the kernel changelog.

    Aside from the hardware devices in /dev, most of the rest of the kernel is accessible from userspace via the /proc virtual filesystem. From there you can read or set all of the kernel parameters, get information about processes such as which fils they have open, etc. See:
    http://www.tldp.org/LDP/Linux-...

    If you ever did need to program for the kernel itself, you do so via a module:
    http://www.tldp.org/LDP/lkmpg/...

    My one credit in the kernel changelog and my one experience with kernel internals, was illustrative of something I've experienced before. I was having a problem with my storage crashing. I was using (abusing?) LVM snapshots, so after following doing what troubleshooting I could, I posted on the LVM mailing list. The LVM maintainer, who is the world's #1 expert on Linux LVM, has me check a couple of things and determined that the problem was likely in the raid module. He suggested I contact the raid devel list. The raid maintainer, who is the #1 expert on Linux raid, looked at it and came up with a fix to the code, which he asked me to try. That worked. I think it's so very cool that the two top experts in the world were so accessible to help me. It didn't cost me a dime. Try that with Windows - try getting the head of Microsoft's storage system programming team to personally assist you. I've found that after I read the documentation such as the appropriate page on tldp.org, the very best of the best Linux developers are always there to help me as long as I follow the advice ESR laid out in http://bettercgi.com/gpl/smart... . Some parts of that document are a bit tongue-in-cheek, or politically incorrect, but it sure does lay out exactly how to get help from very top people.

  33. GOTO is all about readability. by Medievalist · · Score: 1

    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 a specific language's structures and idioms, the less readable the code is. Your code may be the greatest thing ever, but frankly its readability sucks.

    Over the last 40 years I've frequently encountered code in languages I'd never seen before that was perfectly understandable, because the programmer wrote it with human understanding in mind rather than assuming that humans would spend hours studying abstruse syntactica before reading it.

    Elegance in programming is hard. You have to balance the needs of the task, the engine, the user, and the maintenance programmer. Readability is sometimes not achievable without commentry, but truly elegant code is readable.

    An example of coding for readability is to be explicit about order of operations; don't make the reader have to look up precedence of operators in your chosen language, use unnecessary parentheses instead... the compiler will not care and the code will not be less efficient, and you'll reduce opportunities for future human errors.