Kbuild: the Linux Kernel Build System

Listing 3. Coin Character Device Driver Example


#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/device.h>
#include <linux/random.h>
#include <linux/debugfs.h>

#define DEVNAME "coin"
#define LEN  20
enum values {HEAD, TAIL};

struct dentry *dir, *file;
int file_value;
int stats[2] = {0, 0};
char *msg[2] = {"head\n", "tail\n"};

static int major;
static struct class *class_coin;
static struct device *dev_coin;

static ssize_t r_coin(struct file *f, char __user *b,
                      size_t cnt, loff_t *lf)
{
        char *ret;
        u32 value = random32() % 2;
        ret = msg[value];
        stats[value]++;
        return simple_read_from_buffer(b, cnt,
                                       lf, ret,
                                       strlen(ret));
}

static struct file_operations fops = { .read = r_coin };

#ifdef CONFIG_COIN_STAT
static ssize_t r_stat(struct file *f, char __user *b,
                         size_t cnt, loff_t *lf)
{
        char buf[LEN];
        snprintf(buf, LEN, "head=%d tail=%d\n",
                 stats[HEAD], stats[TAIL]);
        return simple_read_from_buffer(b, cnt,
                                       lf, buf,
                                       strlen(buf));
}

static struct file_operations fstat = { .read = r_stat };
#endif

int init_module(void)
{
        void *ptr_err;
        major = register_chrdev(0, DEVNAME, &fops);
        if (major < 0)
                return major;

        class_coin = class_create(THIS_MODULE,
                                  DEVNAME);
        if (IS_ERR(class_coin)) {
                ptr_err = class_coin;
                goto err_class;
        }

        dev_coin = device_create(class_coin, NULL,
                                 MKDEV(major, 0),
                                 NULL, DEVNAME);
        if (IS_ERR(dev_coin))
                goto err_dev;

#ifdef CONFIG_COIN_STAT
        dir = debugfs_create_dir("coin", NULL);
        file = debugfs_create_file("stats", 0644,
                                   dir, &file_value,
                                   &fstat);
#endif

        return 0;
err_dev:
        ptr_err = class_coin;
        class_destroy(class_coin);
err_class:
        unregister_chrdev(major, DEVNAME);
        return PTR_ERR(ptr_err);
}

void cleanup_module(void)
{
#ifdef CONFIG_COIN_STAT
        debugfs_remove(file);
        debugfs_remove(dir);
#endif

        device_destroy(class_coin, MKDEV(major, 0));
        class_destroy(class_coin);
        return unregister_chrdev(major, DEVNAME);
}

In Listing 3, you can see that the CONFIG_COIN_STAT configuration option is used to register (or not) a special debugfs file that exposes the coin-flipping statistics to userspace.

Figure 2 summarizes the kernel build process, and the output of the git diff --stat command shows the files you have modified to include the driver:


drivers/char/Kconfig  |   16 +++++++++
drivers/char/Makefile |    1 +
drivers/char/coin.c   |   89 ++++++++++++++++++++++++++++++++++++++++
3 files changed, 106 insertions(+), 0 deletions(-)

Figure 2. Kernel Build Process

Conclusion

Linux, despite being a monolithic kernel, is highly modular and customizable. You can use the same kernel in a varied range of devices from high-performance clusters to desktops all the way to mobile phones. This makes the kernel a very big and complex piece of software. But, even when the kernel has millions of lines of code, its build system allows you to extend it with new features easily. In the past, to have access to an operating system's source code, you had to work for a big company and sign large NDA agreements. Nowadays, the source of probably the most modern operating system is publicly available. You can use it, study its internals and modify it in any creative way you want. The best part is that you even can share your work and get feedback from an active community. Happy hacking!

______________________

Javier Martinez Canillas is a longtime Linux user, administrator and open-source advocate developer. He has an MS from the Universitat Autònoma de Barcelona and works as a Linux kernel engineer.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Interesting Blog

Systems engineering services's picture

This is really one of the most interesting blog, I've seen so far.

Post new comment Please note

Anonymous's picture

Post new comment
Please note that comments may not appear immediately, so there is no need to repost your comment.IBM's platform as a service (PaaS), IBM SmartCloud Application Services, is now generally available and ready to help your development team collaborate in the cloud!
http://www.lehighvalleylive.com/bethlehem/index.ssf/2008/11/australian_c...

Great Work!

Linux Schulungen's picture

It´s a excellent post, with great insight, and lots to think about Linux. That´s all I could come up with after reading it.
Thank you very much.

query

Anonymous's picture

i have very useful stuff with this article ..you posted a freat stuff about kernel

Reply to comment | Linux Journal

freecriminalattorney.info's picture

Hi there! I just wanted to ask if you ever have any
issues with hackers? My last blog (wordpress) was
hacked and I ended up losing several weeks of hard work due to no back up.
Do you have any solutions to stop hackers?

What's up, after reading this

nevster's picture

What's up, after reading this remarkable paragraph i am also cheerful to share my experience here with mates.
bathmate

advantage doubtfull, disadvantage certain

Anonymous's picture

"I know I will never need, in this build, the drivers for thousands of NIC and printers and whatsoever, Buetooth functions...and whatever.
I have THIS antenna, THIS hard Disk....and so on."

With hard drive space being like $60/TB you'd never recover enough space to make the endeavor worthwhile.

OTOH there is a major disadvantage to your idea. You "never" need *this* network driver, wifi, etc. right now, but what if your motherboard dies? With Windows you hope you can find all your original media and try to reinstall or hope you made a "good" backup that you can restore all your software and settings to a fresh install (something I've never completely succeeded with on Windows, usually not eve close).

With all the drivers in place as modules you can move the drive to a new system and let the auto hardware detection in modern distributions (Knoppix, Ubuntu etc.) get you up and running without effort.

In fact I use this as a feature by "cloning" my development system and then distributing them as "appliance" computers to run my software. Should I need to do "field service" my developent tools and environment are there waiting for me.

I know this will mark me as a

Anonymous's picture

I know this will mark me as a "total noob", but.....

Is there an EASY way to remove ANY UNNECESSARY COMPONENT from the Kernel to suite exactly what needed for my hardware AND preferred applications?

I mean something like a list of checkbox to mark after a deep research on my hardware, that then produce the right system iso to install

I know I will never need, in this build, the drivers for thousands of NIC and printers and whatsoever, Buetooth functions...and whatever.
I have THIS antenna, THIS hard Disk....and so on.

And most of all...there would be any advantage in doing so?

OR....would it be possible to use Synaptic to remove anything unneeded also in kernel? (I already panic when it tells me gnome metapackages must be remove to get rid of the - for me - unuseful Totem...)

Thanks

I know this will mark me as a

Anonymous's picture

I know this will mark me as a "total noob", but.....

Is there an EASY way to remove ANY UNNECESSARY COMPONENT from the Kernel to suite exactly what needed for my hardware AND preferred applications?

I mean something like a list of checkbox to mark after a deep research on my hardware, that then produce the right system iso to install

I know I will never need, in this build, the drivers for thousands of NIC and printers and whatsoever, Buetooth functions...and whatever.
I have THIS antenna, THIS hard Disk....and so on.

And most of all...there would be any advantage in doing so?

OR....would it be possible to use Synaptic to remove anything unneeded also in kernel? (I already panic when it tells me gnome metapackages must be remove to get rid of the - for me - unuseful Totem...)

Thanks

Good article

Anonymous's picture

Good article, thanks for posting it !

Find out where the SD card is

autelcn's picture

Find out where the SD card is mounted to begin the formatting process. Launch a "Terminal" window if you are not already in a terminal shell account. To launch the "Terminal" in Ubuntu Linux, select "Applications" from the menu bar and drag to "Accessories" and then to "Terminal." Release the Mouse button to launch "Terminal."

_______________________
http://www.autelcn.com/
autel ds708

Great article!

Mdturnerinoz's picture

I've played round with kernel builds some but didn't know all this detail until your article: thanks for sharing you insights!

Very informative! +1 for

Marcelo Elizeche Landó's picture

Very informative! +1 for root@sauron

computer science

ma. elena's picture

Excellent article, I recommend it.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState