From 0ad7004d249d5d404a0c023a7f9cbb8548eb484c Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Mon, 26 Sep 2016 14:51:34 +0100 Subject: [PATCH] Examples --- 4.7.4/LKMPG-4.7.4.html | 450 +++++++++++++------------- 4.7.4/LKMPG-4.7.4.org | 31 +- 4.7.4/examples/Makefile | 26 ++ 4.7.4/examples/chardev.c | 166 ++++++++++ 4.7.4/examples/chardev.h | 66 ++++ 4.7.4/examples/chardev2.c | 276 ++++++++++++++++ 4.7.4/examples/file_sched.c | 164 ++++++++++ 4.7.4/examples/flycheck_syscall.plist | 14 + 4.7.4/examples/hello-1.c | 20 ++ 4.7.4/examples/hello-2.c | 21 ++ 4.7.4/examples/hello-3.c | 22 ++ 4.7.4/examples/hello-4.c | 25 ++ 4.7.4/examples/hello-5.c | 70 ++++ 4.7.4/examples/hello-sysfs.c | 68 ++++ 4.7.4/examples/kbleds.c | 95 ++++++ 4.7.4/examples/other/Makefile | 6 + 4.7.4/examples/other/cat_noblock.c | 65 ++++ 4.7.4/examples/other/ioctl.c | 104 ++++++ 4.7.4/examples/print_string.c | 108 +++++++ 4.7.4/examples/procfs1.c | 50 +++ 4.7.4/examples/procfs2.c | 98 ++++++ 4.7.4/examples/procfs3.c | 83 +++++ 4.7.4/examples/procfs4.c | 134 ++++++++ 4.7.4/examples/sleep.c | 265 +++++++++++++++ 4.7.4/examples/start.c | 12 + 4.7.4/examples/stop.c | 11 + 4.7.4/examples/syscall.c | 158 +++++++++ 27 files changed, 2370 insertions(+), 238 deletions(-) create mode 100644 4.7.4/examples/Makefile create mode 100644 4.7.4/examples/chardev.c create mode 100644 4.7.4/examples/chardev.h create mode 100644 4.7.4/examples/chardev2.c create mode 100644 4.7.4/examples/file_sched.c create mode 100644 4.7.4/examples/flycheck_syscall.plist create mode 100644 4.7.4/examples/hello-1.c create mode 100644 4.7.4/examples/hello-2.c create mode 100644 4.7.4/examples/hello-3.c create mode 100644 4.7.4/examples/hello-4.c create mode 100644 4.7.4/examples/hello-5.c create mode 100644 4.7.4/examples/hello-sysfs.c create mode 100644 4.7.4/examples/kbleds.c create mode 100644 4.7.4/examples/other/Makefile create mode 100644 4.7.4/examples/other/cat_noblock.c create mode 100644 4.7.4/examples/other/ioctl.c create mode 100644 4.7.4/examples/print_string.c create mode 100644 4.7.4/examples/procfs1.c create mode 100644 4.7.4/examples/procfs2.c create mode 100644 4.7.4/examples/procfs3.c create mode 100644 4.7.4/examples/procfs4.c create mode 100644 4.7.4/examples/sleep.c create mode 100644 4.7.4/examples/start.c create mode 100644 4.7.4/examples/stop.c create mode 100644 4.7.4/examples/syscall.c diff --git a/4.7.4/LKMPG-4.7.4.html b/4.7.4/LKMPG-4.7.4.html index e40a891..d05679a 100644 --- a/4.7.4/LKMPG-4.7.4.html +++ b/4.7.4/LKMPG-4.7.4.html @@ -3,7 +3,7 @@ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> - + The Linux Kernel Module Programming Guide @@ -264,91 +264,91 @@ for the JavaScript code in this tag.

Table of Contents

-
-

Introduction

-
+
+

Introduction

+

The Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the Open Software License, version 1.1. You can obtain a copy of this license at http://opensource.org/licenses/osl.php.

@@ -370,18 +370,18 @@ If you publish or distribute this book commercially, donations, royalties, and/o

-
-

Authorship

-
+
+

Authorship

+

The Linux Kernel Module Programming Guide was originally written for the 2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to maintain the document. After all, the Linux kernel is a fast moving target. Peter Jay Salzman took over maintenance and updated it for the 2.4 kernels. Eventually, Peter no longer had time to follow developments with the 2.6 kernel, so Michael Burian became a co-maintainer to update the document for the 2.6 kernels. Bob Mottram updated the examples for 3.8 and 4.7.4 kernels and modified or updated some chapters.

-
-

Versioning and Notes

-
+
+

Versioning and Notes

+

The Linux kernel is a moving target. There has always been a question whether the LKMPG should remove deprecated information or keep it around for historical sake. Michael Burian and I decided to create a new branch of the LKMPG for each new stable kernel version. So version LKMPG 4.7.x will address Linux kernel 4.7.4 and LKMPG 2.6.x will address Linux kernel 2.6. No attempt will be made to archive historical information; a person wishing this information should read the appropriately versioned LKMPG.

@@ -392,18 +392,18 @@ The source code and discussions should apply to most architectures, but I can't
-
-

Acknowledgements

-
+
+

Acknowledgements

+

The following people have contributed corrections or good suggestions: Ignacio Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, Francois Audeon, Horst Schirmeier and Bob Mottram.

-
-

What Is A Kernel Module?

-
+
+

What Is A Kernel Module?

+

So, you want to write a kernel module. You know C, you've written a few normal programs to run as processes, and now you want to get to where the real action is, to where a single wild pointer can wipe out your file system and a core dump means a reboot.

@@ -414,9 +414,9 @@ What exactly is a kernel module? Modules are pieces of code that can be loaded a
-
-

Kernel module package

-
+
+

Kernel module package

+

Linux distros provide the commands modprobe, insmod and depmod within a package.

@@ -441,9 +441,9 @@ On Parabola:
-
-

What Modules are in my Kernel?

-
+
+

What Modules are in my Kernel?

+

To discover what modules are already loaded within your current kernel use the command lsmod.

@@ -473,29 +473,29 @@ This can be a long list, and you might prefer to search for something particular
-
-

Do I need to download and compile the kernel?

-
+
+

Do I need to download and compile the kernel?

+

For the purposes of following this guide you don't necessarily need to do that. However, it would be wise to run the examples within a test distro running on a virtual machine in order to avoid any possibility of messing up your system.

-
-

Before We Begin

-
+
+

Before We Begin

+

Before we delve into code, there are a few issues we need to cover. Everyone's system is different and everyone has their own groove. Getting your first "hello world" program to compile and load correctly can sometimes be a trick. Rest assured, after you get over the initial hurdle of doing it for the first time, it will be smooth sailing thereafter.

-
  • Modversioning
    +
    • Modversioning

      A module compiled for one kernel won't load if you boot a different kernel unless you enable CONFIG_MODVERSIONS in the kernel. We won't go into module versioning until later in this guide. Until we cover modversions, the examples in the guide may not work if you're running a kernel with modversioning turned on. However, most stock Linux distro kernels come with it turned on. If you're having trouble loading the modules because of versioning errors, compile a kernel with modversioning turned off.

    • -
    • Using X
      +
    • Using X

      It is highly recommended that you type in, compile and load all the examples this guide discusses. It's also highly recommended you do this from a console. You should not be working on this stuff in X.

      @@ -507,9 +507,9 @@ Modules can't print to the screen like printf() can, but they can log informatio
    -
    -

    Headers

    -
    +
    +

    Headers

    +

    Before you can build anything you'll need to install the header files for your kernel. On Parabola GNU/Linux:

    @@ -540,12 +540,12 @@ This will tell you what kernel header files are available. Then for example:
    -
    -

    Hello World

    -
    -
    -

    The Simplest Module

    -
    +
    +

    Hello World

    +
    +
    +

    The Simplest Module

    +

    Most people learning programming start out with some sort of "hello world" example. I don't know what happens to people who break with this tradition, but I think it's safer not to find out. We'll start with a series of hello world programs that demonstrate the different aspects of the basics of writing a kernel module.

    @@ -688,7 +688,7 @@ Lastly, every kernel module needs to include linux/module.h. We needed to includ

    -
    • Introducing printk()
      +
      • Introducing printk()

        Despite what you might think, printk() was not meant to communicate information to the user, even though we used it for exactly this purpose in hello-1! It happens to be a logging mechanism for the kernel, and is used to log information or give warnings. Therefore, each printk() statement comes with a priority, which is the <1> and KERN_ALERT you see. There are 8 priorities and the kernel has macros for them, so you don't have to use cryptic numbers, and you can view them (and their meanings) in linux/kernel.h. If you don't specify a priority level, the default priority, DEFAULT_MESSAGE_LOGLEVEL, will be used.

        @@ -702,7 +702,7 @@ If the priority is less than int console_loglevel, the message is printed on you

      • -
      • About Compiling
        +
      • About Compiling

        Kernel modules need to be compiled a bit differently from regular userspace apps. Former kernel versions required us to care much about these settings, which are usually stored in Makefiles. Although hierarchically organized, many redundant settings accumulated in sublevel Makefiles and made them large and rather difficult to maintain. Fortunately, there is a new way of doing these things, called kbuild, and the build process for external loadable modules is now fully integrated into the standard kernel build mechanism. To learn more on how to compile modules which are not part of the official kernel (such as all the examples you'll find in this guide), see file linux/Documentation/kbuild/modules.txt.

        @@ -719,9 +719,9 @@ Here's another exercise for the reader. See that comment above the return statem
      -
      -

      Hello and Goodbye

      -
      +
      +

      Hello and Goodbye

      +

      In early kernel versions you had to use the init_module and cleanup_module functions, as in the first hello world example, but these days you can name those anything you want by using the module_init and module_exit macros. These macros are defined in linux/init.h. The only requirement is that your init and cleanup functions must be defined before calling the those macros, otherwise you'll get compilation errors. Here's an example of this technique:

      @@ -773,9 +773,9 @@ Now have a look at linux/drivers/char/Makefile for a real world example. As you
      -
      -

      The __init and __exit Macros

      -
      +
      +

      The __init and __exit Macros

      +

      This demonstrates a feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The __init macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers, but not loadable modules. If you think about when the init function is invoked, this makes perfect sense.

      @@ -820,9 +820,9 @@ module_exit(hello_3_exit);
      -
      -

      Licensing and Module Documentation

      -
      +
      +

      Licensing and Module Documentation

      +

      Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this:

      @@ -874,9 +874,9 @@ module_exit(cleanup_hello_4);
      -
      -

      Passing Command Line Arguments to a Module

      -
      +
      +

      Passing Command Line Arguments to a Module

      +

      Modules can take command line arguments, but not with the argc/argv you might be used to.

      @@ -1026,9 +1026,9 @@ hello-5.o: invalid argument syntax for mylong: 'h'
      -
      -

      Modules Spanning Multiple Files

      -
      +
      +

      Modules Spanning Multiple Files

      +

      Sometimes it makes sense to divide a kernel module between several source files.

      @@ -1099,9 +1099,9 @@ This is the complete makefile for all the examples we've seen so far. The first
      -
      -

      Building modules for a precompiled kernel

      -
      +
      +

      Building modules for a precompiled kernel

      +

      Obviously, we strongly suggest you to recompile your kernel, so that you can enable a number of useful debugging features, such as forced module unloading (MODULE_FORCE_UNLOAD): when this option is enabled, you can force the kernel to unload a module even when it believes it is unsafe, via a sudo rmmod -f module command. This option can save you a lot of time and a number of reboots during the development of a module. If you don't want to recompile your kernel then you should consider running the examples within a test distro on a virtual machine. If you mess anything up then you can easily reboot or restore the VM.

      @@ -1193,12 +1193,12 @@ If you do not desire to actually compile the kernel, you can interrupt the build
      -
      -

      Preliminaries

      -
      -
      -

      How modules begin and end

      -
      +
      +

      Preliminaries

      +
      +
      +

      How modules begin and end

      +

      A program usually begins with a main() function, executes a bunch of instructions and terminates upon completion of those instructions. Kernel modules work a bit differently. A module always begin with either the init_module or the function you specify with module_init call. This is the entry function for modules; it tells the kernel what functionality the module provides and sets up the kernel to run the module's functions when they're needed. Once it does this, entry function returns and the module does nothing until the kernel wants to do something with the code that the module provides.

      @@ -1213,9 +1213,9 @@ Every module must have an entry function and an exit function. Since there's mor
      -
      -

      Functions available to modules

      -
      +
      +

      Functions available to modules

      +

      Programmers use functions they don't define all the time. A prime example of this is printf(). You use these library functions which are provided by the standard C library, libc. The definitions for these functions don't actually enter your program until the linking stage, which insures that the code (for printf() for example) is available, and fixes the call instruction to point to that code.

      @@ -1249,9 +1249,9 @@ You can even write modules to replace the kernel's system calls, which we'll do
      -
      -

      User Space vs Kernel Space

      -
      +
      +

      User Space vs Kernel Space

      +

      A kernel is all about access to resources, whether the resource in question happens to be a video card, a hard drive or even memory. Programs often compete for the same resource. As I just saved this document, updatedb started updating the locate database. My vim session and updatedb are both using the hard drive concurrently. The kernel needs to keep things orderly, and not give users access to resources whenever they feel like it. To this end, a CPU can run in different modes. Each mode gives a different level of freedom to do what you want on the system. The Intel 80386 architecture had 4 of these modes, which were called rings. Unix uses only two rings; the highest ring (ring 0, also known as `supervisor mode' where everything is allowed to happen) and the lowest ring, which is called `user mode'.

      @@ -1262,9 +1262,9 @@ Recall the discussion about library functions vs system calls. Typically, you us
      -
      -

      Name Space

      -
      +
      +

      Name Space

      +

      When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you're writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples' global variables; some of the variable names can clash. When a program has lots of global variables which aren't meaningful enough to be distinguished, you get namespace pollution. In large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.

      @@ -1279,9 +1279,9 @@ The file /proc/kallsyms holds all the symbols that the kernel knows about
      -
      -

      Code space

      -
      +
      +

      Code space

      +

      Memory management is a very complicated subject and the majority of O'Reilly's "Understanding The Linux Kernel" exclusively covers memory management! We're not setting out to be experts on memory managements, but we do need to know a couple of facts to even begin worrying about writing real modules.

      @@ -1300,15 +1300,15 @@ By the way, I would like to point out that the above discussion is true for any
      -
      -

      Device Drivers

      -
      +
      +

      Device Drivers

      +

      One class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is represented by a file located in /dev named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the es1370.o sound card device driver might connect the /dev/sound device file to the Ensoniq IS1370 sound card. A userspace program like mp3blaster can use /dev/sound without ever knowing what kind of sound card is installed.

      -
      • Major and Minor Numbers
        +
        • Major and Minor Numbers

          Let's look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive:

          @@ -1371,12 +1371,12 @@ By now you can look at these two device files and know instantly that they are b
        -
        -

        Character Device drivers

        -
        -
        -

        The file_operations Structure

        -
        +
        +

        Character Device drivers

        +
        +
        +

        The file_operations Structure

        +

        The file_operations structure is defined in /usr/include/linux/fs.h, and holds pointers to functions defined by the driver that perform various operations on the device. Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.

        @@ -1461,9 +1461,9 @@ An instance of struct file_operations containing pointers to functions that are
        -
        -

        The file structure

        -
        +
        +

        The file structure

        +

        Each device is represented in the kernel by a file structure, which is defined in linux/fs.h. Be aware that a file is a kernel level structure and never appears in a user space program. It's not the same thing as a FILE, which is defined by glibc and would never appear in a kernel space function. Also, its name is a bit misleading; it represents an abstract open `file', not a file on a disk, which is represented by a structure named inode.

        @@ -1478,9 +1478,9 @@ Go ahead and look at the definition of file. Most of the entries you see, like s
        -
        -

        Registering A Device

        -
        +
        +

        Registering A Device

        +

        As discussed earlier, char devices are accessed through device files, usually located in /dev[7]. The major number tells you which driver handles which device file. The minor number is used only by the driver itself to differentiate which device it's operating on, just in case the driver handles more than one device.

        @@ -1508,9 +1508,9 @@ If you pass a major number of 0 to register_chrdev, the return value will be the
        -
        -

        Unregistering A Device

        -
        +
        +

        Unregistering A Device

        +

        We can't allow the kernel module to be rmmod'ed whenever root feels like it. If the device file is opened by a process and then we remove the kernel module, using the file would cause a call to the memory location where the appropriate function (read/write) used to be. If we're lucky, no other code was loaded there, and we'll get an ugly error message. If we're unlucky, another kernel module was loaded into the same location, which means a jump into the middle of another function within the kernel. The results of this would be impossible to predict, but they can't be very positive.

        @@ -1530,9 +1530,9 @@ It's important to keep the counter accurate; if you ever do lose track of the co
        -
        -

        chardev.c

        -
        +
        +

        chardev.c

        +

        The next code sample creates a char driver named chardev. You can cat its device file.

        @@ -1718,9 +1718,9 @@ The next code sample creates a char driver named chardev. You can cat its device
        -
        -

        Writing Modules for Multiple Kernel Versions

        -
        +
        +

        Writing Modules for Multiple Kernel Versions

        +

        The system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions. A new system call may be added, but usually the old ones will behave exactly like they used to. This is necessary for backward compatibility – a new kernel version is not supposed to break regular processes. In most cases, the device files will also remain the same. On the other hand, the internal interfaces within the kernel can and do change between versions.

        @@ -1744,9 +1744,9 @@ You might already have noticed that recent kernels look different. In case you h
        -
        -

        The /proc File System

        -
        +
        +

        The /proc File System

        +

        In Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes — the /proc file system. Originally designed to allow easy access to information about processes (hence the name), it is now used by every bit of the kernel which has something interesting to report, such as /proc/modules which provides the list of modules and /proc/meminfo which stats memory usage statistics.

        @@ -1836,9 +1836,9 @@ HelloWorld!
        -
        -

        Read and Write a /proc File

        -
        +
        +

        Read and Write a /proc File

        +

        We have seen a very simple example for a /proc file where we only read the file /proc/helloworld. It's also possible to write in a /proc file. It works the same way as read, a function is called when the /proc file is written. But there is a little difference with read, data comes from user, so you have to import data from user space to kernel space (with copy_from_user or get_user)

        @@ -1955,9 +1955,9 @@ The only memory segment accessible to a process is its own, so when writing regu
        -
        -

        Manage /proc file with standard filesystem

        -
        +
        +

        Manage /proc file with standard filesystem

        +

        We have seen how to read and write a /proc file with the /proc interface. But it's also possible to manage /proc file with inodes. The main concern is to use advanced functions, like permissions.

        @@ -2067,9 +2067,9 @@ Still hungry for procfs examples? Well, first of all keep in mind, there are rum
        -
        -

        Manage /proc file with seq_file

        -
        +
        +

        Manage /proc file with seq_file

        +

        As we have seen, writing a /proc file may be quite "complex". So to help people writting /proc file, there is an API named seq_file that helps @@ -2259,9 +2259,9 @@ You can also read the code of fs/seq_file.c in the linux kernel.

        -
        -

        sysfs: Interacting with your module

        -
        +
        +

        sysfs: Interacting with your module

        +

        sysfs allows you to interact with the running kernel by reading or setting variables inside of modules. This can be useful for debugging purposes, or just as an interface for userland applications or scripts.

        @@ -2391,9 +2391,9 @@ Finally, remove the test module:
        -
        -

        Talking To Device Files

        -
        +
        +

        Talking To Device Files

        +

        Device files are supposed to represent physical devices. Most physical devices are used for output as well as input, so there has to be some mechanism for device drivers in the kernel to get the output to send to the device from processes. This is done by opening the device file for output and writing to it, just like writing to a file. In the following example, this is implemented by device_write.

        @@ -2416,7 +2416,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
        /*
        - *  chardev.c - Create an input/output character device
        + *  chardev2.c - Create an input/output character device
          */
         
         #include <linux/kernel.h>       /* We're doing kernel work */
        @@ -2424,7 +2424,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
         #include <linux/fs.h>
         #include <asm/uaccess.h>        /* for get_user and put_user */
         
        -#include "chardev.h"
        +#include "chardev2.h"
         #define SUCCESS 0
         #define DEVICE_NAME "char_dev"
         #define BUF_LEN 80
        @@ -2696,7 +2696,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
         
         
        /*
        - *  chardev.h - the header file with the ioctl definitions.
        + *  chardev2.h - the header file with the ioctl definitions.
          *
          *  The declarations here have to be in a header file, because
          *  they need to be known both to the kernel module
        @@ -2870,9 +2870,9 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
         
        -
        -

        System Calls

        -
        +
        +

        System Calls

        +

        So far, the only thing we've done was to use well defined kernel mechanisms to register /proc files and device handlers. This is fine if you want to do something the kernel programmers thought you'd want, such as write a device driver. But what if you want to do something unusual, to change the behavior of the system in some way? Then, you're mostly on your own.

        @@ -3080,9 +3080,9 @@ asmlinkage int our
        -
        -

        Blocking Processes

        -
        +
        +

        Blocking Processes

        +

        What do you do when somebody asks you for something you can't do right away? If you're a human being and you're bothered by a human being, the only thing you can say is: "Not right now, I'm busy. Go away!". But if you're a kernel module and you're bothered by a process, you have another possibility. You can put the process to sleep until you can service it. After all, processes are being put to sleep by the kernel and woken up all the time (that's the way multiple processes appear to run on the same time on a single CPU).

        @@ -3471,12 +3471,12 @@ DECLARE_WAIT_QUEUE_HEAD(WaitQ);
        -
        -

        Replacing Printks

        -
        -
        -

        Replacing printk

        -
        +
        +

        Replacing Printks

        +
        +
        +

        Replacing printk

        +

        In Section 1.2.1.2, I said that X and kernel module programming don't mix. That's true for developing kernel modules, but in actual use, you want to be able to send messages to whichever tty[15] the command to load the module came from.

        @@ -3599,9 +3599,9 @@ module_exit(print_string_exit);
        -
        -

        Flashing keyboard LEDs

        -
        +
        +

        Flashing keyboard LEDs

        +

        In certain conditions, you may desire a simpler and more direct way to communicate to the external world. Flashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition. Keyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file.

        @@ -3720,9 +3720,9 @@ While you have seen lots of stuff that can be used to aid debugging here, there
        -
        -

        Scheduling Tasks

        -
        +
        +

        Scheduling Tasks

        +

        Very often, we have "housekeeping" tasks which have to be done at a certain time, or every so often. If the task is to be done by a process, we do it by putting it in the crontab file. If the task is to be done by a kernel module, we have two possibilities. The first is to put a process in the crontab file which will wake up the module by a system call when necessary, for example by opening a file. This is terribly inefficient, however – we run a new process off of crontab, read a new executable to memory, and all this just to wake up a kernel module which is in memory anyway.

        @@ -3905,12 +3905,12 @@ MODULE_LICENSE("GPL");
        -
        -

        Interrupt Handlers

        -
        -
        -

        Interrupt Handlers

        -
        +
        +

        Interrupt Handlers

        +
        +
        +

        Interrupt Handlers

        +

        Except for the last chapter, everything we did in the kernel so far we've done as a response to a process asking for it, either by dealing with a special file, sending an ioctl(), or issuing a system call. But the job of the kernel isn't just to respond to process requests. Another job, which is every bit as important, is to speak to the hardware connected to the machine.

        @@ -3937,9 +3937,9 @@ Then, from within the interrupt handler, we communicate with the hardware and th
        -
        -

        Keyboards on the Intel Architecture

        -
        +
        +

        Keyboards on the Intel Architecture

        +

        The rest of this chapter is completely Intel specific. If you're not running on an Intel platform, it will not work. Don't even try to compile the code here. Move right along, nothing to see.

        @@ -4073,35 +4073,35 @@ MODULE_LICENSE("GPL");
        -
        -

        Common Pitfalls

        -
        +
        +

        Common Pitfalls

        +

        Before I send you on your way to go out into the world and write kernel modules, there are a few things I need to warn you about. If I fail to warn you and something bad happens, please report the problem to me for a full refund of the amount I was paid for your copy of the book.

        -
        -

        Using standard libraries

        -
        +
        +

        Using standard libraries

        +

        You can't do that. In a kernel module you can only use kernel functions, which are the functions you can see in /proc/kallsyms.

        -
        -

        Disabling interrupts

        -
        +
        +

        Disabling interrupts

        +

        You might need to do this for a short time and that is OK, but if you don't enable them afterwards, your system will be stuck and you'll have to power it off.

        -
        -

        Sticking your head inside a large carnivore

        -
        +
        +

        Sticking your head inside a large carnivore

        +

        I probably don't have to warn you about this, but I figured I will anyway, just in case.

        @@ -4109,9 +4109,9 @@ I probably don't have to warn you about this, but I figured I will anyway, just
        -
        -

        Where To Go From Here?

        -
        +
        +

        Where To Go From Here?

        +

        I could easily have squeezed a few more chapters into this book. I could have added a chapter about creating new file systems, or about adding new protocol stacks (as if there's a need for that – you'd have to dig underground to find a protocol stack not supported by Linux). I could have added explanations of the kernel mechanisms we haven't touched upon, such as bootstrapping or the disk interface.

        @@ -4134,9 +4134,9 @@ If you'd like to contribute to this guide, please contact one the maintainers fo
        -
        -

        Notes

        -
        +
        +

        Notes

        +

        [1] In earlier versions of linux, this was known as kerneld. [2] If such a file exists. Note that the acual behavoir might be @@ -4205,9 +4205,9 @@ If you'd like to contribute to this guide, please contact one the maintainers fo

        -
        -

        Edits

        -
        +
        +

        Edits

        +

        linux/fs.h updated file_operations structure (see http://lwn.net/Articles/119652/) unregister_chrdev returns void diff --git a/4.7.4/LKMPG-4.7.4.org b/4.7.4/LKMPG-4.7.4.org index c22d858..af3ad87 100644 --- a/4.7.4/LKMPG-4.7.4.org +++ b/4.7.4/LKMPG-4.7.4.org @@ -103,7 +103,7 @@ apt-cache search linux-headers-$(uname -r) This will tell you what kernel header files are available. Then for example: #+BEGIN_SRC sh -sudo apt-get install linux-headers-4.7.4-1-amd64 +sudo apt-get install kmod linux-headers-4.7.4-1-amd64 #+END_SRC * Hello World @@ -1551,9 +1551,9 @@ The ioctl number encodes the major device number, the type of the ioctl, the com If you want to use ioctls in your own kernel modules, it is best to receive an official ioctl assignment, so if you accidentally get somebody else's ioctls, or if they get yours, you'll know something is wrong. For more information, consult the kernel source tree at Documentation/ioctl-number.txt. -#+BEGIN_SRC c :file chardev.c +#+BEGIN_SRC c :file chardev2.c /* - * chardev.c - Create an input/output character device + * chardev2.c - Create an input/output character device */ #include /* We're doing kernel work */ @@ -1561,7 +1561,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o #include #include /* for get_user and put_user */ -#include "chardev.h" +#include "chardev2.h" #define SUCCESS 0 #define DEVICE_NAME "char_dev" #define BUF_LEN 80 @@ -1923,19 +1923,20 @@ void cleanup_module() * Functions for the ioctl calls */ -ioctl_set_msg(int file_desc, char *message) +int ioctl_set_msg(int file_desc, char *message) { int ret_val; ret_val = ioctl(file_desc, IOCTL_SET_MSG, message); - if (ret_val < 0) { - printf("ioctl_set_msg failed:%d\n", ret_val); - exit(-1); - } + if (ret_val < 0) { + printf("ioctl_set_msg failed:%d\n", ret_val); + exit(-1); + } + return 0; } -ioctl_get_msg(int file_desc) +int ioctl_get_msg(int file_desc) { int ret_val; char message[100]; @@ -1956,9 +1957,10 @@ ioctl_get_msg(int file_desc) } printf("get_msg message:%s\n", message); + return 0; } -ioctl_get_nth_byte(int file_desc) +int ioctl_get_nth_byte(int file_desc) { int i; char c; @@ -1978,12 +1980,13 @@ ioctl_get_nth_byte(int file_desc) putchar(c); } while (c != 0); putchar('\n'); + return 0; } /* * Main - Call the ioctl functions */ -main() +int main() { int file_desc, ret_val; char *msg = "Message passed by ioctl\n"; @@ -1999,6 +2002,7 @@ main() ioctl_set_msg(file_desc, msg); close(file_desc); + return 0; } #+END_SRC @@ -2504,7 +2508,7 @@ void cleanup_module() #define MAX_BYTES 1024*4 -main(int argc, char *argv[]) +int main(int argc, char *argv[]) { int fd; /* The file descriptor for the file to read */ size_t bytes; /* The number of bytes read */ @@ -2554,6 +2558,7 @@ main(int argc, char *argv[]) /* While there are no errors and the file isn't over */ } while (bytes > 0); + return 0; } #+END_SRC diff --git a/4.7.4/examples/Makefile b/4.7.4/examples/Makefile new file mode 100644 index 0000000..f9c0d77 --- /dev/null +++ b/4.7.4/examples/Makefile @@ -0,0 +1,26 @@ +obj-m += hello-1.o +obj-m += hello-2.o +obj-m += hello-3.o +obj-m += hello-4.o +obj-m += hello-5.o +obj-m += startstop.o +startstop-objs := start.o stop.o +obj-m += chardev.o +obj-m += procfs1.o +obj-m += procfs2.o +obj-m += procfs3.o +obj-m += procfs4.o +obj-m += hello-sysfs.o +obj-m += sleep.o +obj-m += print_string.o +obj-m += kbleds.o +obj-m += file_sched.o +obj-m += chardev2.o +obj-m += syscall.o + +all: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules + +clean: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean + rm other/ioctl other/cat_noblock diff --git a/4.7.4/examples/chardev.c b/4.7.4/examples/chardev.c new file mode 100644 index 0000000..6150651 --- /dev/null +++ b/4.7.4/examples/chardev.c @@ -0,0 +1,166 @@ +/* + * chardev.c: Creates a read-only char device that says how many times + * you've read from the dev file + */ + +#include +#include +#include +#include /* for put_user */ + +/* + * Prototypes - this would normally go in a .h file + */ +int init_module(void); +void cleanup_module(void); +static int device_open(struct inode *, struct file *); +static int device_release(struct inode *, struct file *); +static ssize_t device_read(struct file *, char *, size_t, loff_t *); +static ssize_t device_write(struct file *, const char *, size_t, loff_t *); + +#define SUCCESS 0 +#define DEVICE_NAME "chardev" /* Dev name as it appears in /proc/devices */ +#define BUF_LEN 80 /* Max length of the message from the device */ + +/* + * Global variables are declared as static, so are global within the file. + */ + +static int Major; /* Major number assigned to our device driver */ +static int Device_Open = 0; /* Is device open? + * Used to prevent multiple access to device */ +static char msg[BUF_LEN]; /* The msg the device will give when asked */ +static char *msg_Ptr; + +static struct file_operations fops = { + .read = device_read, + .write = device_write, + .open = device_open, + .release = device_release +}; + +/* + * This function is called when the module is loaded + */ +int init_module(void) +{ + Major = register_chrdev(0, DEVICE_NAME, &fops); + + if (Major < 0) { + printk(KERN_ALERT "Registering char device failed with %d\n", Major); + return Major; + } + + printk(KERN_INFO "I was assigned major number %d. To talk to\n", Major); + printk(KERN_INFO "the driver, create a dev file with\n"); + printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, Major); + printk(KERN_INFO "Try various minor numbers. Try to cat and echo to\n"); + printk(KERN_INFO "the device file.\n"); + printk(KERN_INFO "Remove the device file and module when done.\n"); + + return SUCCESS; +} + +/* + * This function is called when the module is unloaded + */ +void cleanup_module(void) +{ + /* + * Unregister the device + */ + unregister_chrdev(Major, DEVICE_NAME); +} + +/* + * Methods + */ + +/* + * Called when a process tries to open the device file, like + * "cat /dev/mycharfile" + */ +static int device_open(struct inode *inode, struct file *file) +{ + static int counter = 0; + + if (Device_Open) + return -EBUSY; + + Device_Open++; + sprintf(msg, "I already told you %d times Hello world!\n", counter++); + msg_Ptr = msg; + try_module_get(THIS_MODULE); + + return SUCCESS; +} + +/* + * Called when a process closes the device file. + */ +static int device_release(struct inode *inode, struct file *file) +{ + Device_Open--; /* We're now ready for our next caller */ + + /* + * Decrement the usage count, or else once you opened the file, you'll + * never get get rid of the module. + */ + module_put(THIS_MODULE); + + return 0; +} + +/* + * Called when a process, which already opened the dev file, attempts to + * read from it. + */ +static ssize_t device_read(struct file *filp, /* see include/linux/fs.h */ + char *buffer, /* buffer to fill with data */ + size_t length, /* length of the buffer */ + loff_t * offset) +{ + /* + * Number of bytes actually written to the buffer + */ + int bytes_read = 0; + + /* + * If we're at the end of the message, + * return 0 signifying end of file + */ + if (*msg_Ptr == 0) + return 0; + + /* + * Actually put the data into the buffer + */ + while (length && *msg_Ptr) { + + /* + * The buffer is in the user data segment, not the kernel + * segment so "*" assignment won't work. We have to use + * put_user which copies data from the kernel data segment to + * the user data segment. + */ + put_user(*(msg_Ptr++), buffer++); + + length--; + bytes_read++; + } + + /* + * Most read functions return the number of bytes put into the buffer + */ + return bytes_read; +} + +/* + * Called when a process writes to dev file: echo "hi" > /dev/hello + */ +static ssize_t +device_write(struct file *filp, const char *buff, size_t len, loff_t * off) +{ + printk(KERN_ALERT "Sorry, this operation isn't supported.\n"); + return -EINVAL; +} diff --git a/4.7.4/examples/chardev.h b/4.7.4/examples/chardev.h new file mode 100644 index 0000000..1df613c --- /dev/null +++ b/4.7.4/examples/chardev.h @@ -0,0 +1,66 @@ +/* + * chardev2.h - the header file with the ioctl definitions. + * + * The declarations here have to be in a header file, because + * they need to be known both to the kernel module + * (in chardev.c) and the process calling ioctl (ioctl.c) + */ + +#ifndef CHARDEV_H +#define CHARDEV_H + +#include + +/* + * The major device number. We can't rely on dynamic + * registration any more, because ioctls need to know + * it. + */ +#define MAJOR_NUM 100 + +/* + * Set the message of the device driver + */ +#define IOCTL_SET_MSG _IOR(MAJOR_NUM, 0, char *) +/* + * _IOR means that we're creating an ioctl command + * number for passing information from a user process + * to the kernel module. + * + * The first arguments, MAJOR_NUM, is the major device + * number we're using. + * + * The second argument is the number of the command + * (there could be several with different meanings). + * + * The third argument is the type we want to get from + * the process to the kernel. + */ + +/* + * Get the message of the device driver + */ +#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *) +/* + * This IOCTL is used for output, to get the message + * of the device driver. However, we still need the + * buffer to place the message in to be input, + * as it is allocated by the process. + */ + +/* + * Get the n'th byte of the message + */ +#define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int) +/* + * The IOCTL is used for both input and output. It + * receives from the user a number, n, and returns + * Message[n]. + */ + +/* + * The name of the device file + */ +#define DEVICE_FILE_NAME "char_dev" + +#endif diff --git a/4.7.4/examples/chardev2.c b/4.7.4/examples/chardev2.c new file mode 100644 index 0000000..b0c4c49 --- /dev/null +++ b/4.7.4/examples/chardev2.c @@ -0,0 +1,276 @@ +/* + * chardev2.c - Create an input/output character device + */ + +#include /* We're doing kernel work */ +#include /* Specifically, a module */ +#include +#include /* for get_user and put_user */ + +#include "chardev.h" +#define SUCCESS 0 +#define DEVICE_NAME "char_dev" +#define BUF_LEN 80 + +/* + * Is the device open right now? Used to prevent + * concurent access into the same device + */ +static int Device_Open = 0; + +/* + * The message the device will give when asked + */ +static char Message[BUF_LEN]; + +/* + * How far did the process reading the message get? + * Useful if the message is larger than the size of the + * buffer we get to fill in device_read. + */ +static char *Message_Ptr; + +/* + * This is called whenever a process attempts to open the device file + */ +static int device_open(struct inode *inode, struct file *file) +{ +#ifdef DEBUG + printk(KERN_INFO "device_open(%p)\n", file); +#endif + + /* + * We don't want to talk to two processes at the same time + */ + if (Device_Open) + return -EBUSY; + + Device_Open++; + /* + * Initialize the message + */ + Message_Ptr = Message; + try_module_get(THIS_MODULE); + return SUCCESS; +} + +static int device_release(struct inode *inode, struct file *file) +{ +#ifdef DEBUG + printk(KERN_INFO "device_release(%p,%p)\n", inode, file); +#endif + + /* + * We're now ready for our next caller + */ + Device_Open--; + + module_put(THIS_MODULE); + return SUCCESS; +} + +/* + * This function is called whenever a process which has already opened the + * device file attempts to read from it. + */ +static ssize_t device_read(struct file *file, /* see include/linux/fs.h */ + char __user * buffer, /* buffer to be + * filled with data */ + size_t length, /* length of the buffer */ + loff_t * offset) +{ + /* + * Number of bytes actually written to the buffer + */ + int bytes_read = 0; + +#ifdef DEBUG + printk(KERN_INFO "device_read(%p,%p,%d)\n", file, buffer, length); +#endif + + /* + * If we're at the end of the message, return 0 + * (which signifies end of file) + */ + if (*Message_Ptr == 0) + return 0; + + /* + * Actually put the data into the buffer + */ + while (length && *Message_Ptr) { + + /* + * Because the buffer is in the user data segment, + * not the kernel data segment, assignment wouldn't + * work. Instead, we have to use put_user which + * copies data from the kernel data segment to the + * user data segment. + */ + put_user(*(Message_Ptr++), buffer++); + length--; + bytes_read++; +} + +#ifdef DEBUG + printk(KERN_INFO "Read %d bytes, %d left\n", bytes_read, length); +#endif + + /* + * Read functions are supposed to return the number + * of bytes actually inserted into the buffer + */ + return bytes_read; +} + +/* + * This function is called when somebody tries to + * write into our device file. + */ +static ssize_t +device_write(struct file *file, + const char __user * buffer, size_t length, loff_t * offset) +{ + int i; + +#ifdef DEBUG + printk(KERN_INFO "device_write(%p,%s,%d)", file, buffer, length); +#endif + + for (i = 0; i < length && i < BUF_LEN; i++) + get_user(Message[i], buffer + i); + + Message_Ptr = Message; + + /* + * Again, return the number of input characters used + */ + return i; +} + +/* + * This function is called whenever a process tries to do an ioctl on our + * device file. We get two extra parameters (additional to the inode and file + * structures, which all device functions get): the number of the ioctl called + * and the parameter given to the ioctl function. + * + * If the ioctl is write or read/write (meaning output is returned to the + * calling process), the ioctl call returns the output of this function. + * + */ +long device_ioctl(struct file *file, /* ditto */ + unsigned int ioctl_num, /* number and param for ioctl */ + unsigned long ioctl_param) +{ + int i; + char *temp; + char ch; + + /* + * Switch according to the ioctl called + */ + switch (ioctl_num) { + case IOCTL_SET_MSG: + /* + * Receive a pointer to a message (in user space) and set that + * to be the device's message. Get the parameter given to + * ioctl by the process. + */ + temp = (char *)ioctl_param; + + /* + * Find the length of the message + */ + get_user(ch, temp); + for (i = 0; ch && i < BUF_LEN; i++, temp++) + get_user(ch, temp); + + device_write(file, (char *)ioctl_param, i, 0); + break; + + case IOCTL_GET_MSG: + /* + * Give the current message to the calling process - + * the parameter we got is a pointer, fill it. + */ + i = device_read(file, (char *)ioctl_param, 99, 0); + + /* + * Put a zero at the end of the buffer, so it will be + * properly terminated + */ + put_user('\0', (char *)ioctl_param + i); + break; + + case IOCTL_GET_NTH_BYTE: + /* + * This ioctl is both input (ioctl_param) and + * output (the return value of this function) + */ + return Message[ioctl_param]; + break; + } + + return SUCCESS; +} + +/* Module Declarations */ + +/* + * This structure will hold the functions to be called + * when a process does something to the device we + * created. Since a pointer to this structure is kept in + * the devices table, it can't be local to + * init_module. NULL is for unimplemented functions. + */ +struct file_operations Fops = { + .read = device_read, + .write = device_write, + .unlocked_ioctl = device_ioctl, + .open = device_open, + .release = device_release, /* a.k.a. close */ +}; + +/* + * Initialize the module - Register the character device + */ +int init_module() +{ + int ret_val; + /* + * Register the character device (atleast try) + */ + ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &Fops); + + /* + * Negative values signify an error + */ + if (ret_val < 0) { + printk(KERN_ALERT "%s failed with %d\n", + "Sorry, registering the character device ", ret_val); + return ret_val; + } + + printk(KERN_INFO "%s The major device number is %d.\n", + "Registeration is a success", MAJOR_NUM); + printk(KERN_INFO "If you want to talk to the device driver,\n"); + printk(KERN_INFO "you'll have to create a device file. \n"); + printk(KERN_INFO "We suggest you use:\n"); + printk(KERN_INFO "mknod %s c %d 0\n", DEVICE_FILE_NAME, MAJOR_NUM); + printk(KERN_INFO "The device file name is important, because\n"); + printk(KERN_INFO "the ioctl program assumes that's the\n"); + printk(KERN_INFO "file you'll use.\n"); + + return 0; +} + +/* + * Cleanup - unregister the appropriate file from /proc + */ +void cleanup_module() +{ + /* + * Unregister the device + */ + unregister_chrdev(MAJOR_NUM, DEVICE_NAME); +} diff --git a/4.7.4/examples/file_sched.c b/4.7.4/examples/file_sched.c new file mode 100644 index 0000000..60f3576 --- /dev/null +++ b/4.7.4/examples/file_sched.c @@ -0,0 +1,164 @@ +/* + * sched.c - scheduale a function to be called on every timer interrupt. + * + * Copyright (C) 2001 by Peter Jay Salzman + */ + +/* + * The necessary header files + */ + +/* + * Standard in kernel modules + */ +#include /* We're doing kernel work */ +#include /* Specifically, a module */ +#include /* Necessary because we use the proc fs */ +#include /* We scheduale tasks here */ +#include /* We need to put ourselves to sleep + and wake up later */ +#include /* For __init and __exit */ +#include /* For irqreturn_t */ + +struct proc_dir_entry *Our_Proc_File; +#define PROC_ENTRY_FILENAME "sched" +#define MY_WORK_QUEUE_NAME "WQsched.c" + +/* + * some work_queue related functions + * are just available to GPL licensed Modules + */ +MODULE_LICENSE("GPL"); + +/* + * The number of times the timer interrupt has been called so far + */ +static int TimerIntrpt = 0; + +static void intrpt_routine(struct work_struct *work); + +static int die = 0; /* set this to 1 for shutdown */ + +/* + * The work queue structure for this task, from workqueue.h + */ +static struct workqueue_struct *my_workqueue; + +static struct delayed_work Task; +static DECLARE_DELAYED_WORK(Task, intrpt_routine); + +/* + * This function will be called on every timer interrupt. Notice the void* + * pointer - task functions can be used for more than one purpose, each time + * getting a different parameter. + */ +static void intrpt_routine(struct work_struct *work) +{ + /* + * Increment the counter + */ + TimerIntrpt++; + + /* + * If cleanup wants us to die + */ + if (die == 0) + queue_delayed_work(my_workqueue, &Task, 100); +} + +/* + * Put data into the proc fs file. + */ +int +procfile_read(char *buffer, + char **buffer_location, + off_t offset, int buffer_length, int *eof, void *data) +{ + int len; /* The number of bytes actually used */ + + /* + * It's static so it will still be in memory + * when we leave this function + */ + static char my_buffer[80]; + + /* + * We give all of our information in one go, so if anybody asks us + * if we have more information the answer should always be no. + */ + if (offset > 0) + return 0; + + /* + * Fill the buffer and get its length + */ + len = sprintf(my_buffer, "Timer called %d times so far\n", TimerIntrpt); + + /* + * Tell the function which called us where the buffer is + */ + *buffer_location = my_buffer; + + /* + * Return the length + */ + return len; +} + +/* + * Initialize the module - register the proc file + */ +int __init init_module() +{ + /* + * Create our /proc file + */ + Our_Proc_File = proc_create(PROC_ENTRY_FILENAME, 0644, NULL, NULL); + + if (Our_Proc_File == NULL) { + remove_proc_entry(PROC_ENTRY_FILENAME, NULL); + printk(KERN_ALERT "Error: Could not initialize /proc/%s\n", + PROC_ENTRY_FILENAME); + return -ENOMEM; + } + proc_set_size(Our_Proc_File, 80); + proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID); + + /* + * Put the task in the work_timer task queue, so it will be executed at + * next timer interrupt + */ + my_workqueue = create_workqueue(MY_WORK_QUEUE_NAME); + queue_delayed_work(my_workqueue, &Task, 100); + + printk(KERN_INFO "/proc/%s created\n", PROC_ENTRY_FILENAME); + + return 0; +} + +/* + * Cleanup + */ +void __exit cleanup_module() +{ + /* + * Unregister our /proc file + */ + remove_proc_entry(PROC_ENTRY_FILENAME, NULL); + printk(KERN_INFO "/proc/%s removed\n", PROC_ENTRY_FILENAME); + + die = 1; /* keep intrp_routine from queueing itself */ + cancel_delayed_work(&Task); /* no "new ones" */ + flush_workqueue(my_workqueue); /* wait till all "old ones" finished */ + destroy_workqueue(my_workqueue); + + /* + * Sleep until intrpt_routine is called one last time. This is + * necessary, because otherwise we'll deallocate the memory holding + * intrpt_routine and Task while work_timer still references them. + * Notice that here we don't allow signals to interrupt us. + * + * Since WaitQ is now not NULL, this automatically tells the interrupt + * routine it's time to die. + */ +} diff --git a/4.7.4/examples/flycheck_syscall.plist b/4.7.4/examples/flycheck_syscall.plist new file mode 100644 index 0000000..655f648 --- /dev/null +++ b/4.7.4/examples/flycheck_syscall.plist @@ -0,0 +1,14 @@ + + + + + clang_version +clang version 3.8.1 (tags/RELEASE_381/final) + files + + + diagnostics + + + + \ No newline at end of file diff --git a/4.7.4/examples/hello-1.c b/4.7.4/examples/hello-1.c new file mode 100644 index 0000000..e10024f --- /dev/null +++ b/4.7.4/examples/hello-1.c @@ -0,0 +1,20 @@ +/* + * hello-1.c - The simplest kernel module. + */ +#include /* Needed by all modules */ +#include /* Needed for KERN_INFO */ + +int init_module(void) +{ + printk(KERN_INFO "Hello world 1.\n"); + + /* + * A non 0 return means init_module failed; module can't be loaded. + */ + return 0; +} + +void cleanup_module(void) +{ + printk(KERN_INFO "Goodbye world 1.\n"); +} diff --git a/4.7.4/examples/hello-2.c b/4.7.4/examples/hello-2.c new file mode 100644 index 0000000..00012b8 --- /dev/null +++ b/4.7.4/examples/hello-2.c @@ -0,0 +1,21 @@ +/* + * hello-2.c - Demonstrating the module_init() and module_exit() macros. + * This is preferred over using init_module() and cleanup_module(). + */ +#include /* Needed by all modules */ +#include /* Needed for KERN_INFO */ +#include /* Needed for the macros */ + +static int __init hello_2_init(void) +{ + printk(KERN_INFO "Hello, world 2\n"); + return 0; +} + +static void __exit hello_2_exit(void) +{ + printk(KERN_INFO "Goodbye, world 2\n"); +} + +module_init(hello_2_init); +module_exit(hello_2_exit); diff --git a/4.7.4/examples/hello-3.c b/4.7.4/examples/hello-3.c new file mode 100644 index 0000000..6b7be08 --- /dev/null +++ b/4.7.4/examples/hello-3.c @@ -0,0 +1,22 @@ +/* + * hello-3.c - Illustrating the __init, __initdata and __exit macros. + */ +#include /* Needed by all modules */ +#include /* Needed for KERN_INFO */ +#include /* Needed for the macros */ + +static int hello3_data __initdata = 3; + +static int __init hello_3_init(void) +{ + printk(KERN_INFO "Hello, world %d\n", hello3_data); + return 0; +} + +static void __exit hello_3_exit(void) +{ + printk(KERN_INFO "Goodbye, world 3\n"); +} + +module_init(hello_3_init); +module_exit(hello_3_exit); diff --git a/4.7.4/examples/hello-4.c b/4.7.4/examples/hello-4.c new file mode 100644 index 0000000..269cec1 --- /dev/null +++ b/4.7.4/examples/hello-4.c @@ -0,0 +1,25 @@ +/* + * hello-4.c - Demonstrates module documentation. + */ +#include /* Needed by all modules */ +#include /* Needed for KERN_INFO */ +#include /* Needed for the macros */ + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Bob Mottram"); +MODULE_DESCRIPTION("A sample driver"); +MODULE_SUPPORTED_DEVICE("testdevice"); + +static int __init init_hello_4(void) +{ + printk(KERN_INFO "Hello, world 4\n"); + return 0; +} + +static void __exit cleanup_hello_4(void) +{ + printk(KERN_INFO "Goodbye, world 4\n"); +} + +module_init(init_hello_4); +module_exit(cleanup_hello_4); diff --git a/4.7.4/examples/hello-5.c b/4.7.4/examples/hello-5.c new file mode 100644 index 0000000..8ffabb3 --- /dev/null +++ b/4.7.4/examples/hello-5.c @@ -0,0 +1,70 @@ +/* + * hello-5.c - Demonstrates command line argument passing to a module. + */ +#include +#include +#include +#include +#include + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Peter Jay Salzman"); + +static short int myshort = 1; +static int myint = 420; +static long int mylong = 9999; +static char *mystring = "blah"; +static int myintArray[2] = { -1, -1 }; +static int arr_argc = 0; + +/* + * module_param(foo, int, 0000) + * The first param is the parameters name + * The second param is it's data type + * The final argument is the permissions bits, + * for exposing parameters in sysfs (if non-zero) at a later stage. + */ + +module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); +MODULE_PARM_DESC(myshort, "A short integer"); +module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); +MODULE_PARM_DESC(myint, "An integer"); +module_param(mylong, long, S_IRUSR); +MODULE_PARM_DESC(mylong, "A long integer"); +module_param(mystring, charp, 0000); +MODULE_PARM_DESC(mystring, "A character string"); + +/* + * module_param_array(name, type, num, perm); + * The first param is the parameter's (in this case the array's) name + * The second param is the data type of the elements of the array + * The third argument is a pointer to the variable that will store the number + * of elements of the array initialized by the user at module loading time + * The fourth argument is the permission bits + */ +module_param_array(myintArray, int, &arr_argc, 0000); +MODULE_PARM_DESC(myintArray, "An array of integers"); + +static int __init hello_5_init(void) +{ + int i; + printk(KERN_INFO "Hello, world 5\n=============\n"); + printk(KERN_INFO "myshort is a short integer: %hd\n", myshort); + printk(KERN_INFO "myint is an integer: %d\n", myint); + printk(KERN_INFO "mylong is a long integer: %ld\n", mylong); + printk(KERN_INFO "mystring is a string: %s\n", mystring); + for (i = 0; i < (sizeof myintArray / sizeof (int)); i++) + { + printk(KERN_INFO "myintArray[%d] = %d\n", i, myintArray[i]); + } + printk(KERN_INFO "got %d arguments for myintArray.\n", arr_argc); + return 0; +} + +static void __exit hello_5_exit(void) +{ + printk(KERN_INFO "Goodbye, world 5\n"); +} + +module_init(hello_5_init); +module_exit(hello_5_exit); diff --git a/4.7.4/examples/hello-sysfs.c b/4.7.4/examples/hello-sysfs.c new file mode 100644 index 0000000..ac15d45 --- /dev/null +++ b/4.7.4/examples/hello-sysfs.c @@ -0,0 +1,68 @@ +/* + * hello-sysfs.c sysfs example + */ + +#include +#include +#include +#include +#include +#include +#include + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Bob Mottram"); + +static struct kobject *mymodule; + +/* the variable you want to be able to change */ +static int myvariable = 0; + +static ssize_t myvariable_show(struct kobject *kobj, + struct kobj_attribute *attr, + char *buf) +{ + return sprintf(buf, "%d\n", myvariable); +} + +static ssize_t myvariable_store(struct kobject *kobj, + struct kobj_attribute *attr, + char *buf, size_t count) +{ + sscanf(buf, "%du", &myvariable); + return count; +} + + +static struct kobj_attribute myvariable_attribute = + __ATTR(myvariable, 0660, myvariable_show, + (void*)myvariable_store); + +static int __init mymodule_init (void) +{ + int error = 0; + + printk(KERN_INFO "mymodule: initialised\n"); + + mymodule = + kobject_create_and_add("mymodule", kernel_kobj); + if (!mymodule) + return -ENOMEM; + + error = sysfs_create_file(mymodule, &myvariable_attribute.attr); + if (error) { + printk(KERN_INFO "failed to create the myvariable file " \ + "in /sys/kernel/mymodule\n"); + } + + return error; +} + +static void __exit mymodule_exit (void) +{ + printk(KERN_INFO "mymodule: Exit success\n"); + kobject_put(mymodule); +} + +module_init(mymodule_init); +module_exit(mymodule_exit); diff --git a/4.7.4/examples/kbleds.c b/4.7.4/examples/kbleds.c new file mode 100644 index 0000000..baf1a8c --- /dev/null +++ b/4.7.4/examples/kbleds.c @@ -0,0 +1,95 @@ +/* + * kbleds.c - Blink keyboard leds until the module is unloaded. + */ + +#include +#include +#include /* for fg_console */ +#include /* For fg_console, MAX_NR_CONSOLES */ +#include /* For KDSETLED */ +#include +#include /* For vc_cons */ + +MODULE_DESCRIPTION("Example module illustrating the use of Keyboard LEDs."); +MODULE_AUTHOR("Daniele Paolo Scarpazza"); +MODULE_LICENSE("GPL"); + +struct timer_list my_timer; +struct tty_driver *my_driver; +char kbledstatus = 0; + +#define BLINK_DELAY HZ/5 +#define ALL_LEDS_ON 0x07 +#define RESTORE_LEDS 0xFF + +/* + * Function my_timer_func blinks the keyboard LEDs periodically by invoking + * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual + * terminal ioctl operations, please see file: + * /usr/src/linux/drivers/char/vt_ioctl.c, function vt_ioctl(). + * + * The argument to KDSETLED is alternatively set to 7 (thus causing the led + * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF + * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus + * the LEDs reflect the actual keyboard status). To learn more on this, + * please see file: + * /usr/src/linux/drivers/char/keyboard.c, function setledstate(). + * + */ + +static void my_timer_func(unsigned long ptr) +{ + unsigned long *pstatus = (unsigned long *)ptr; + struct tty_struct* t = vc_cons[fg_console].d->port.tty; + + if (*pstatus == ALL_LEDS_ON) + *pstatus = RESTORE_LEDS; + else + *pstatus = ALL_LEDS_ON; + + (my_driver->ops->ioctl) (t, KDSETLED, *pstatus); + + my_timer.expires = jiffies + BLINK_DELAY; + add_timer(&my_timer); +} + +static int __init kbleds_init(void) +{ + int i; + + printk(KERN_INFO "kbleds: loading\n"); + printk(KERN_INFO "kbleds: fgconsole is %x\n", fg_console); + for (i = 0; i < MAX_NR_CONSOLES; i++) { + if (!vc_cons[i].d) + break; + printk(KERN_INFO "poet_atkm: console[%i/%i] #%i, tty %lx\n", i, + MAX_NR_CONSOLES, vc_cons[i].d->vc_num, + (unsigned long)vc_cons[i].d->port.tty); + } + printk(KERN_INFO "kbleds: finished scanning consoles\n"); + + my_driver = vc_cons[fg_console].d->port.tty->driver; + printk(KERN_INFO "kbleds: tty driver magic %x\n", my_driver->magic); + + /* + * Set up the LED blink timer the first time + */ + init_timer(&my_timer); + my_timer.function = my_timer_func; + my_timer.data = (unsigned long)&kbledstatus; + my_timer.expires = jiffies + BLINK_DELAY; + add_timer(&my_timer); + + return 0; +} + +static void __exit kbleds_cleanup(void) +{ + printk(KERN_INFO "kbleds: unloading...\n"); + del_timer(&my_timer); + (my_driver->ops->ioctl) (vc_cons[fg_console].d->port.tty, + KDSETLED, RESTORE_LEDS); +} + +module_init(kbleds_init); +module_exit(kbleds_cleanup); diff --git a/4.7.4/examples/other/Makefile b/4.7.4/examples/other/Makefile new file mode 100644 index 0000000..98135b3 --- /dev/null +++ b/4.7.4/examples/other/Makefile @@ -0,0 +1,6 @@ +all: + gcc -o cat_noblock cat_noblock.c + gcc -o ioctl ioctl.c + +clean: + rm ioctl cat_noblock *.plist diff --git a/4.7.4/examples/other/cat_noblock.c b/4.7.4/examples/other/cat_noblock.c new file mode 100644 index 0000000..7cd453d --- /dev/null +++ b/4.7.4/examples/other/cat_noblock.c @@ -0,0 +1,65 @@ +/* cat_noblock.c - open a file and display its contents, but exit rather than + * wait for input */ +/* Copyright (C) 1998 by Ori Pomerantz */ + +#include /* standard I/O */ +#include /* for open */ +#include /* for read */ +#include /* for exit */ +#include /* for errno */ + +#define MAX_BYTES 1024*4 + + +int main(int argc, char *argv[]) +{ + int fd; /* The file descriptor for the file to read */ + size_t bytes; /* The number of bytes read */ + char buffer[MAX_BYTES]; /* The buffer for the bytes */ + + + /* Usage */ + if (argc != 2) { + printf("Usage: %s \n", argv[0]); + puts("Reads the content of a file, but doesn't wait for input"); + exit(-1); + } + + /* Open the file for reading in non blocking mode */ + fd = open(argv[1], O_RDONLY | O_NONBLOCK); + + /* If open failed */ + if (fd == -1) { + if (errno = EAGAIN) + puts("Open would block"); + else + puts("Open failed"); + exit(-1); + } + + /* Read the file and output its contents */ + do { + int i; + + /* Read characters from the file */ + bytes = read(fd, buffer, MAX_BYTES); + + /* If there's an error, report it and die */ + if (bytes == -1) { + if (errno = EAGAIN) + puts("Normally I'd block, but you told me not to"); + else + puts("Another read error"); + exit(-1); + } + + /* Print the characters */ + if (bytes > 0) { + for(i=0; i 0); + return 0; +} diff --git a/4.7.4/examples/other/ioctl.c b/4.7.4/examples/other/ioctl.c new file mode 100644 index 0000000..28b245e --- /dev/null +++ b/4.7.4/examples/other/ioctl.c @@ -0,0 +1,104 @@ +/* + * ioctl.c - the process to use ioctl's to control the kernel module + * + * Until now we could have used cat for input and output. But now + * we need to do ioctl's, which require writing our own process. + */ + +/* + * device specifics, such as ioctl numbers and the + * major device file. + */ +#include "../chardev.h" + +#include +#include +#include /* open */ +#include /* exit */ +#include /* ioctl */ + +/* + * Functions for the ioctl calls + */ + +int ioctl_set_msg(int file_desc, char *message) +{ + int ret_val; + + ret_val = ioctl(file_desc, IOCTL_SET_MSG, message); + + if (ret_val < 0) { + printf("ioctl_set_msg failed:%d\n", ret_val); + exit(-1); + } + return 0; +} + +int ioctl_get_msg(int file_desc) +{ + int ret_val; + char message[100]; + + /* + * Warning - this is dangerous because we don't tell + * the kernel how far it's allowed to write, so it + * might overflow the buffer. In a real production + * program, we would have used two ioctls - one to tell + * the kernel the buffer length and another to give + * it the buffer to fill + */ + ret_val = ioctl(file_desc, IOCTL_GET_MSG, message); + + if (ret_val < 0) { + printf("ioctl_get_msg failed:%d\n", ret_val); + exit(-1); + } + + printf("get_msg message:%s\n", message); + return 0; +} + +int ioctl_get_nth_byte(int file_desc) +{ + int i; + char c; + + printf("get_nth_byte message:"); + + i = 0; + do { + c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++); + + if (c < 0) { + printf("ioctl_get_nth_byte failed at the %d'th byte:\n", + i); + exit(-1); + } + + putchar(c); + } while (c != 0); + putchar('\n'); + return 0; +} + +/* + * Main - Call the ioctl functions + */ +int main() +{ + int file_desc, ret_val; + char *msg = "Message passed by ioctl\n"; + + file_desc = open(DEVICE_FILE_NAME, 0); + if (file_desc < 0) { + printf("Can't open device file: %s\n", DEVICE_FILE_NAME); + exit(-1); + } + + ioctl_get_nth_byte(file_desc); + ioctl_get_msg(file_desc); + ioctl_set_msg(file_desc, msg); + + close(file_desc); + return 0; +} diff --git a/4.7.4/examples/print_string.c b/4.7.4/examples/print_string.c new file mode 100644 index 0000000..4f5dadb --- /dev/null +++ b/4.7.4/examples/print_string.c @@ -0,0 +1,108 @@ +/* + * print_string.c - Send output to the tty we're running on, regardless if it's + * through X11, telnet, etc. We do this by printing the string to the tty + * associated with the current task. + */ +#include +#include +#include +#include /* For current */ +#include /* For the tty declarations */ +#include /* For LINUX_VERSION_CODE */ + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Peter Jay Salzman"); + +static void print_string(char *str) +{ + struct tty_struct *my_tty; + const struct tty_operations *ttyops; + + /* + * tty struct went into signal struct in 2.6.6 + */ +#if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,5) ) + /* + * The tty for the current task + */ + my_tty = current->tty; +#else + /* + * The tty for the current task, for 2.6.6+ kernels + */ + my_tty = current->signal->tty; +#endif + ttyops = my_tty->driver->ops; + + /* + * If my_tty is NULL, the current task has no tty you can print to + * (ie, if it's a daemon). If so, there's nothing we can do. + */ + if (my_tty != NULL) { + + /* + * my_tty->driver is a struct which holds the tty's functions, + * one of which (write) is used to write strings to the tty. + * It can be used to take a string either from the user's or + * kernel's memory segment. + * + * The function's 1st parameter is the tty to write to, + * because the same function would normally be used for all + * tty's of a certain type. The 2nd parameter controls + * whether the function receives a string from kernel + * memory (false, 0) or from user memory (true, non zero). + * BTW: this param has been removed in Kernels > 2.6.9 + * The (2nd) 3rd parameter is a pointer to a string. + * The (3rd) 4th parameter is the length of the string. + * + * As you will see below, sometimes it's necessary to use + * preprocessor stuff to create code that works for different + * kernel versions. The (naive) approach we've taken here + * does not scale well. The right way to deal with this + * is described in section 2 of + * linux/Documentation/SubmittingPatches + */ + (ttyops->write) (my_tty, /* The tty itself */ +#if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) ) + 0, /* Don't take the string + from user space */ +#endif + str, /* String */ + strlen(str)); /* Length */ + + /* + * ttys were originally hardware devices, which (usually) + * strictly followed the ASCII standard. In ASCII, to move to + * a new line you need two characters, a carriage return and a + * line feed. On Unix, the ASCII line feed is used for both + * purposes - so we can't just use \n, because it wouldn't have + * a carriage return and the next line will start at the + * column right after the line feed. + * + * This is why text files are different between Unix and + * MS Windows. In CP/M and derivatives, like MS-DOS and + * MS Windows, the ASCII standard was strictly adhered to, + * and therefore a newline requirs both a LF and a CR. + */ + +#if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) ) + (ttyops->write) (my_tty, 0, "\015\012", 2); +#else + (ttyops->write) (my_tty, "\015\012", 2); +#endif + } +} + +static int __init print_string_init(void) +{ + print_string("The module has been inserted. Hello world!"); + return 0; +} + +static void __exit print_string_exit(void) +{ + print_string("The module has been removed. Farewell world!"); +} + +module_init(print_string_init); +module_exit(print_string_exit); diff --git a/4.7.4/examples/procfs1.c b/4.7.4/examples/procfs1.c new file mode 100644 index 0000000..bd8ece2 --- /dev/null +++ b/4.7.4/examples/procfs1.c @@ -0,0 +1,50 @@ +/* + procfs1.c +*/ + +#include +#include +#include +#include + +#define procfs_name "helloworld" + +struct proc_dir_entry *Our_Proc_File; + + +ssize_t procfile_read(struct file *filePointer,char *buffer, + size_t buffer_length, loff_t * offset) +{ + int ret=0; + if(strlen(buffer) ==0) { + printk(KERN_INFO "procfile read %s\n",filePointer->f_path.dentry->d_name.name); + ret=copy_to_user(buffer,"HelloWorld!\n",sizeof("HelloWorld!\n")); + ret=sizeof("HelloWorld!\n"); + } + return ret; + +} + +static const struct file_operations proc_file_fops = { + .owner = THIS_MODULE, + .read = procfile_read, +}; + +int init_module() +{ + Our_Proc_File = proc_create(procfs_name,0644,NULL,&proc_file_fops); + if(NULL==Our_Proc_File) { + proc_remove(Our_Proc_File); + printk(KERN_ALERT "Error:Could not initialize /proc/%s\n",procfs_name); + return -ENOMEM; + } + + printk(KERN_INFO "/proc/%s created\n", procfs_name); + return 0; +} + +void cleanup_module() +{ + proc_remove(Our_Proc_File); + printk(KERN_INFO "/proc/%s removed\n", procfs_name); +} diff --git a/4.7.4/examples/procfs2.c b/4.7.4/examples/procfs2.c new file mode 100644 index 0000000..eac0a57 --- /dev/null +++ b/4.7.4/examples/procfs2.c @@ -0,0 +1,98 @@ +/** + * procfs2.c - create a "file" in /proc + * + */ + +#include /* Specifically, a module */ +#include /* We're doing kernel work */ +#include /* Necessary because we use the proc fs */ +#include /* for copy_from_user */ + +#define PROCFS_MAX_SIZE 1024 +#define PROCFS_NAME "buffer1k" + +/** + * This structure hold information about the /proc file + * + */ +static struct proc_dir_entry *Our_Proc_File; + +/** + * The buffer used to store character for this module + * + */ +static char procfs_buffer[PROCFS_MAX_SIZE]; + +/** + * The size of the buffer + * + */ +static unsigned long procfs_buffer_size = 0; + +/** + * This function is called then the /proc file is read + * + */ +ssize_t procfile_read(struct file *filePointer,char *buffer, + size_t buffer_length, loff_t * offset) +{ + int ret=0; + if(strlen(buffer) ==0) { + printk(KERN_INFO "procfile read %s\n",filePointer->f_path.dentry->d_name.name); + ret=copy_to_user(buffer,"HelloWorld!\n",sizeof("HelloWorld!\n")); + ret=sizeof("HelloWorld!\n"); + } + return ret; +} + + +/** + * This function is called with the /proc file is written + * + */ +static ssize_t procfile_write(struct file *file, const char *buff, + size_t len, loff_t *off) +{ + procfs_buffer_size = len; + if (procfs_buffer_size > PROCFS_MAX_SIZE) + procfs_buffer_size = PROCFS_MAX_SIZE; + + if (copy_from_user(procfs_buffer, buff, procfs_buffer_size)) + return -EFAULT; + + procfs_buffer[procfs_buffer_size] = '\0'; + return procfs_buffer_size; +} + +static const struct file_operations proc_file_fops = { + .owner = THIS_MODULE, + .read = procfile_read, + .write = procfile_write, +}; + +/** + *This function is called when the module is loaded + * + */ +int init_module() +{ + Our_Proc_File = proc_create(PROCFS_NAME,0644,NULL,&proc_file_fops); + if(NULL==Our_Proc_File) { + proc_remove(Our_Proc_File); + printk(KERN_ALERT "Error:Could not initialize /proc/%s\n",PROCFS_NAME); + return -ENOMEM; + } + + printk(KERN_INFO "/proc/%s created\n", PROCFS_NAME); + return 0; +} + +/** + *This function is called when the module is unloaded + * + */ +void cleanup_module() +{ + proc_remove(Our_Proc_File); + printk(KERN_INFO "/proc/%s removed\n", PROCFS_NAME); +} diff --git a/4.7.4/examples/procfs3.c b/4.7.4/examples/procfs3.c new file mode 100644 index 0000000..11a4f62 --- /dev/null +++ b/4.7.4/examples/procfs3.c @@ -0,0 +1,83 @@ +/* + procfs3.c +*/ + +#include +#include +#include +#include +#include + +#define PROCFS_MAX_SIZE 2048 +#define PROCFS_ENTRY_FILENAME "buffer2k" + +struct proc_dir_entry *Our_Proc_File; +static char procfs_buffer[PROCFS_MAX_SIZE]; +static unsigned long procfs_buffer_size = 0; + +static ssize_t procfs_read(struct file *filp, char *buffer, + size_t length, loff_t *offset) +{ + static int finished = 0; + if(finished) + { + printk(KERN_DEBUG "procfs_read: END\n"); + finished = 0; + return 0; + } + finished = 1; + if(copy_to_user(buffer, procfs_buffer, procfs_buffer_size)) + return -EFAULT; + printk(KERN_DEBUG "procfs_read: read %lu bytes\n", procfs_buffer_size); + return procfs_buffer_size; +} +static ssize_t procfs_write(struct file *file, const char *buffer, + size_t len, loff_t *off) +{ + if(len>PROCFS_MAX_SIZE) + procfs_buffer_size = PROCFS_MAX_SIZE; + else + procfs_buffer_size = len; + if(copy_from_user(procfs_buffer, buffer, procfs_buffer_size)) + return -EFAULT; + printk(KERN_DEBUG "procfs_write: write %lu bytes\n", procfs_buffer_size); + return procfs_buffer_size; +} +int procfs_open(struct inode *inode, struct file *file) +{ + try_module_get(THIS_MODULE); + return 0; +} +int procfs_close(struct inode *inode, struct file *file) +{ + module_put(THIS_MODULE); + return 0; +} + +static struct file_operations File_Ops_4_Our_Proc_File = { + .read = procfs_read, + .write = procfs_write, + .open = procfs_open, + .release = procfs_close, +}; + +int init_module() +{ + Our_Proc_File = proc_create(PROCFS_ENTRY_FILENAME, 0644, NULL,&File_Ops_4_Our_Proc_File); + if(Our_Proc_File == NULL) + { + remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL); + printk(KERN_DEBUG "Error: Could not initialize /proc/%s\n", PROCFS_ENTRY_FILENAME); + return -ENOMEM; + } + proc_set_size(Our_Proc_File, 80); + proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID); + + printk(KERN_DEBUG "/proc/%s created\n", PROCFS_ENTRY_FILENAME); + return 0; +} +void cleanup_module() +{ + remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL); + printk(KERN_DEBUG "/proc/%s removed\n", PROCFS_ENTRY_FILENAME); +} diff --git a/4.7.4/examples/procfs4.c b/4.7.4/examples/procfs4.c new file mode 100644 index 0000000..369fb31 --- /dev/null +++ b/4.7.4/examples/procfs4.c @@ -0,0 +1,134 @@ +/** + * procfs4.c - create a "file" in /proc + * This program uses the seq_file library to manage the /proc file. + * + */ + +#include /* We're doing kernel work */ +#include /* Specifically, a module */ +#include /* Necessary because we use proc fs */ +#include /* for seq_file */ + +#define PROC_NAME "iter" + +MODULE_AUTHOR("Philippe Reynes"); +MODULE_LICENSE("GPL"); + +/** + * This function is called at the beginning of a sequence. + * ie, when: + * - the /proc file is read (first time) + * - after the function stop (end of sequence) + * + */ +static void *my_seq_start(struct seq_file *s, loff_t *pos) +{ + static unsigned long counter = 0; + + /* beginning a new sequence ? */ + if ( *pos == 0 ) { + /* yes => return a non null value to begin the sequence */ + return &counter; + } + else { + /* no => it's the end of the sequence, return end to stop reading */ + *pos = 0; + return NULL; + } +} + +/** + * This function is called after the beginning of a sequence. + * It's called untill the return is NULL (this ends the sequence). + * + */ +static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos) +{ + unsigned long *tmp_v = (unsigned long *)v; + (*tmp_v)++; + (*pos)++; + return NULL; +} + +/** + * This function is called at the end of a sequence + * + */ +static void my_seq_stop(struct seq_file *s, void *v) +{ + /* nothing to do, we use a static value in start() */ +} + +/** + * This function is called for each "step" of a sequence + * + */ +static int my_seq_show(struct seq_file *s, void *v) +{ + loff_t *spos = (loff_t *) v; + + seq_printf(s, "%Ld\n", *spos); + return 0; +} + +/** + * This structure gather "function" to manage the sequence + * + */ +static struct seq_operations my_seq_ops = { + .start = my_seq_start, + .next = my_seq_next, + .stop = my_seq_stop, + .show = my_seq_show +}; + +/** + * This function is called when the /proc file is open. + * + */ +static int my_open(struct inode *inode, struct file *file) +{ + return seq_open(file, &my_seq_ops); +}; + +/** + * This structure gather "function" that manage the /proc file + * + */ +static struct file_operations my_file_ops = { + .owner = THIS_MODULE, + .open = my_open, + .read = seq_read, + .llseek = seq_lseek, + .release = seq_release +}; + + +/** + * This function is called when the module is loaded + * + */ +int init_module(void) +{ + struct proc_dir_entry *entry; + + entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops); + if(entry == NULL) + { + remove_proc_entry(PROC_NAME, NULL); + printk(KERN_DEBUG "Error: Could not initialize /proc/%s\n", PROC_NAME); + return -ENOMEM; + } + + return 0; +} + +/** + * This function is called when the module is unloaded. + * + */ +void cleanup_module(void) +{ + remove_proc_entry(PROC_NAME, NULL); + printk(KERN_DEBUG "/proc/%s removed\n", PROC_NAME); +} diff --git a/4.7.4/examples/sleep.c b/4.7.4/examples/sleep.c new file mode 100644 index 0000000..513e599 --- /dev/null +++ b/4.7.4/examples/sleep.c @@ -0,0 +1,265 @@ +/* + * sleep.c - create a /proc file, and if several processes try to open it at + * the same time, put all but one to sleep + */ + +#include /* We're doing kernel work */ +#include /* Specifically, a module */ +#include /* Necessary because we use proc fs */ +#include /* For putting processes to sleep and + waking them up */ +#include /* for get_user and put_user */ + +/* + * The module's file functions + */ + +/* + * Here we keep the last message received, to prove that we can process our + * input + */ +#define MESSAGE_LENGTH 80 +static char Message[MESSAGE_LENGTH]; + +static struct proc_dir_entry *Our_Proc_File; +#define PROC_ENTRY_FILENAME "sleep" + +/* + * Since we use the file operations struct, we can't use the special proc + * output provisions - we have to use a standard read function, which is this + * function + */ +static ssize_t module_output(struct file *file, /* see include/linux/fs.h */ + char *buf, /* The buffer to put data to + (in the user segment) */ + size_t len, /* The length of the buffer */ + loff_t * offset) +{ + static int finished = 0; + int i; + char message[MESSAGE_LENGTH + 30]; + + /* + * Return 0 to signify end of file - that we have nothing + * more to say at this point. + */ + if (finished) { + finished = 0; + return 0; + } + + /* + * If you don't understand this by now, you're hopeless as a kernel + * programmer. + */ + sprintf(message, "Last input:%s\n", Message); + for (i = 0; i < len && message[i]; i++) + put_user(message[i], buf + i); + + finished = 1; + return i; /* Return the number of bytes "read" */ +} + +/* + * This function receives input from the user when the user writes to the /proc + * file. + */ +static ssize_t module_input(struct file *file, /* The file itself */ + const char *buf, /* The buffer with input */ + size_t length, /* The buffer's length */ + loff_t * offset) /* offset to file - ignore */ +{ + int i; + + /* + * Put the input into Message, where module_output will later be + * able to use it + */ + for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++) + get_user(Message[i], buf + i); + /* + * we want a standard, zero terminated string + */ + Message[i] = '\0'; + + /* + * We need to return the number of input characters used + */ + return i; +} + +/* + * 1 if the file is currently open by somebody + */ +int Already_Open = 0; + +/* + * Queue of processes who want our file + */ +DECLARE_WAIT_QUEUE_HEAD(WaitQ); +/* + * Called when the /proc file is opened + */ +static int module_open(struct inode *inode, struct file *file) +{ + /* + * If the file's flags include O_NONBLOCK, it means the process doesn't + * want to wait for the file. In this case, if the file is already + * open, we should fail with -EAGAIN, meaning "you'll have to try + * again", instead of blocking a process which would rather stay awake. + */ + if ((file->f_flags & O_NONBLOCK) && Already_Open) + return -EAGAIN; + + /* + * This is the correct place for try_module_get(THIS_MODULE) because + * if a process is in the loop, which is within the kernel module, + * the kernel module must not be removed. + */ + try_module_get(THIS_MODULE); + + /* + * If the file is already open, wait until it isn't + */ + + while (Already_Open) { + int i, is_sig = 0; + + /* + * This function puts the current process, including any system + * calls, such as us, to sleep. Execution will be resumed right + * after the function call, either because somebody called + * wake_up(&WaitQ) (only module_close does that, when the file + * is closed) or when a signal, such as Ctrl-C, is sent + * to the process + */ + wait_event_interruptible(WaitQ, !Already_Open); + + /* + * If we woke up because we got a signal we're not blocking, + * return -EINTR (fail the system call). This allows processes + * to be killed or stopped. + */ + + /* + * Emmanuel Papirakis: + * + * This is a little update to work with 2.2.*. Signals now are contained in + * two words (64 bits) and are stored in a structure that contains an array of + * two unsigned longs. We now have to make 2 checks in our if. + * + * Ori Pomerantz: + * + * Nobody promised me they'll never use more than 64 bits, or that this book + * won't be used for a version of Linux with a word size of 16 bits. This code + * would work in any case. + */ + for (i = 0; i < _NSIG_WORDS && !is_sig; i++) + is_sig = + current->pending.signal.sig[i] & ~current-> + blocked.sig[i]; + + if (is_sig) { + /* + * It's important to put module_put(THIS_MODULE) here, + * because for processes where the open is interrupted + * there will never be a corresponding close. If we + * don't decrement the usage count here, we will be + * left with a positive usage count which we'll have no + * way to bring down to zero, giving us an immortal + * module, which can only be killed by rebooting + * the machine. + */ + module_put(THIS_MODULE); + return -EINTR; + } + } + + /* + * If we got here, Already_Open must be zero + */ + + /* + * Open the file + */ + Already_Open = 1; + return 0; /* Allow the access */ +} + +/* + * Called when the /proc file is closed + */ +int module_close(struct inode *inode, struct file *file) +{ + /* + * Set Already_Open to zero, so one of the processes in the WaitQ will + * be able to set Already_Open back to one and to open the file. All + * the other processes will be called when Already_Open is back to one, + * so they'll go back to sleep. + */ + Already_Open = 0; + + /* + * Wake up all the processes in WaitQ, so if anybody is waiting for the + * file, they can have it. + */ + wake_up(&WaitQ); + + module_put(THIS_MODULE); + + return 0; /* success */ +} + +/* + * Structures to register as the /proc file, with pointers to all the relevant + * functions. + */ + +/* + * File operations for our proc file. This is where we place pointers to all + * the functions called when somebody tries to do something to our file. NULL + * means we don't want to deal with something. + */ +static struct file_operations File_Ops_4_Our_Proc_File = { + .read = module_output, /* "read" from the file */ + .write = module_input, /* "write" to the file */ + .open = module_open, /* called when the /proc file is opened */ + .release = module_close, /* called when it's closed */ +}; + +/* + * Module initialization and cleanup + */ + +/* + * Initialize the module - register the proc file + */ + +int init_module() +{ + Our_Proc_File = proc_create(PROC_ENTRY_FILENAME, 0644, NULL, &File_Ops_4_Our_Proc_File); + if(Our_Proc_File == NULL) + { + remove_proc_entry(PROC_ENTRY_FILENAME, NULL); + printk(KERN_DEBUG "Error: Could not initialize /proc/%s\n", PROC_ENTRY_FILENAME); + return -ENOMEM; + } + proc_set_size(Our_Proc_File, 80); + proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID); + + printk(KERN_INFO "/proc/test created\n"); + + return 0; +} + +/* + * Cleanup - unregister our file from /proc. This could get dangerous if + * there are still processes waiting in WaitQ, because they are inside our + * open function, which will get unloaded. I'll explain how to avoid removal + * of a kernel module in such a case in chapter 10. + */ +void cleanup_module() +{ + remove_proc_entry(PROC_ENTRY_FILENAME, NULL); + printk(KERN_DEBUG "/proc/%s removed\n", PROC_ENTRY_FILENAME); +} diff --git a/4.7.4/examples/start.c b/4.7.4/examples/start.c new file mode 100644 index 0000000..908fc1f --- /dev/null +++ b/4.7.4/examples/start.c @@ -0,0 +1,12 @@ +/* + * start.c - Illustration of multi filed modules + */ + +#include /* We're doing kernel work */ +#include /* Specifically, a module */ + +int init_module(void) +{ + printk(KERN_INFO "Hello, world - this is the kernel speaking\n"); + return 0; +} diff --git a/4.7.4/examples/stop.c b/4.7.4/examples/stop.c new file mode 100644 index 0000000..dcc9b0c --- /dev/null +++ b/4.7.4/examples/stop.c @@ -0,0 +1,11 @@ +/* + * stop.c - Illustration of multi filed modules + */ + +#include /* We're doing kernel work */ +#include /* Specifically, a module */ + +void cleanup_module() +{ + printk(KERN_INFO "Short is the life of a kernel module\n"); +} diff --git a/4.7.4/examples/syscall.c b/4.7.4/examples/syscall.c new file mode 100644 index 0000000..6682a7d --- /dev/null +++ b/4.7.4/examples/syscall.c @@ -0,0 +1,158 @@ +/* + * syscall.c + * + * System call "stealing" sample. + */ + +/* + * Copyright (C) 2001 by Peter Jay Salzman + */ + +/* + * The necessary header files + */ + +/* + * Standard in kernel modules + */ +#include /* We're doing kernel work */ +#include /* Specifically, a module, */ +#include /* which will have params */ +#include /* The list of system calls */ +#include + +/* + * For the current (process) structure, we need + * this to know who the current user is. + */ +#include +#include + +/* + * The system call table (a table of functions). We + * just define this as external, and the kernel will + * fill it up for us when we are insmod'ed + * + * sys_call_table is no longer exported in 2.6.x kernels. + * If you really want to try this DANGEROUS module you will + * have to apply the supplied patch against your current kernel + * and recompile it. + */ +extern void *sys_call_table[]; + +/* + * UID we want to spy on - will be filled from the + * command line + */ +static int uid; +module_param(uid, int, 0644); + +/* + * A pointer to the original system call. The reason + * we keep this, rather than call the original function + * (sys_open), is because somebody else might have + * replaced the system call before us. Note that this + * is not 100% safe, because if another module + * replaced sys_open before us, then when we're inserted + * we'll call the function in that module - and it + * might be removed before we are. + * + * Another reason for this is that we can't get sys_open. + * It's a static variable, so it is not exported. + */ +asmlinkage int (*original_call) (const char *, int, int); + +/* + * The function we'll replace sys_open (the function + * called when you call the open system call) with. To + * find the exact prototype, with the number and type + * of arguments, we find the original function first + * (it's at fs/open.c). + * + * In theory, this means that we're tied to the + * current version of the kernel. In practice, the + * system calls almost never change (it would wreck havoc + * and require programs to be recompiled, since the system + * calls are the interface between the kernel and the + * processes). + */ +asmlinkage int our_sys_open(const char *filename, int flags, int mode) +{ + int i = 0; + char ch; + + /* + * Check if this is the user we're spying on + */ + if (uid == current_uid()) { + /* + * Report the file, if relevant + */ + printk("Opened file by %d: ", uid); + do { + get_user(ch, filename + i); + i++; + printk("%c", ch); + } while (ch != 0); + printk("\n"); + } + + /* + * Call the original sys_open - otherwise, we lose + * the ability to open files + */ + return original_call(filename, flags, mode); +} + +/* + * Initialize the module - replace the system call + */ +int init_module() +{ + /* + * Warning - too late for it now, but maybe for + * next time... + */ + printk(KERN_ALERT "I'm dangerous. I hope you did a "); + printk(KERN_ALERT "sync before you insmod'ed me.\n"); + printk(KERN_ALERT "My counterpart, cleanup_module(), is even"); + printk(KERN_ALERT "more dangerous. If\n"); + printk(KERN_ALERT "you value your file system, it will "); + printk(KERN_ALERT "be \"sync; rmmod\" \n"); + printk(KERN_ALERT "when you remove this module.\n"); + + /* + * Keep a pointer to the original function in + * original_call, and then replace the system call + * in the system call table with our_sys_open + */ + original_call = sys_call_table[__NR_open]; + sys_call_table[__NR_open] = our_sys_open; + + /* + * To get the address of the function for system + * call foo, go to sys_call_table[__NR_foo]. + */ + + printk(KERN_INFO "Spying on UID:%d\n", uid); + + return 0; +} + +/* + * Cleanup - unregister the appropriate file from /proc + */ +void cleanup_module() +{ + /* + * Return the system call back to normal + */ + if (sys_call_table[__NR_open] != our_sys_open) { + printk(KERN_ALERT "Somebody else also played with the "); + printk(KERN_ALERT "open system call\n"); + printk(KERN_ALERT "The system may be left in "); + printk(KERN_ALERT "an unstable state.\n"); + } + + sys_call_table[__NR_open] = original_call; +}