#include <linux/init.h>
#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h> /* printk() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/fs.h> /* everything... */
#include <linux/errno.h> /* error codes */
#include <linux/types.h> /* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h> /* O_ACCMODE */
#include <asm/system.h> /* cli(), *_flags */
#include <asm/uaccess.h> /* copy_from/to_user */
MODULE_LICENSE("Dual BSD/GPL");
/* Declaration of memory.c functions */
int memory_open(struct inode *inode, struct file *filp);
int memory_release(struct inode *inode, struct file *filp);
ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);
ssize_t memory_write(struct file *filp, char *buf, size_t count, loff_t *f_pos);
void memory_exit(void);
int memory_init(void);
/* Structure that declares the usual file */
/* access functions */
struct file_operations memory_fops = {
read: memory_read,
write: memory_write,
open: memory_open,
release: memory_release
};
/* Declaration of the init and exit functions */
module_init(memory_init);
module_exit(memory_exit);
/* Global variables of the driver */
/* Major number */
int memory_major = 60;
/* Buffer to store data */
char *memory_buffer;
After the #include files, the functions that will be defined later are declared. The common functions which
are typically used to manipulate files are declared in the definition of the file_operations structure.
These will also be explained in detail later. Next, the initialization and exit functions—used when loading and
removing the module—are declared to the kernel. Finally, the global variables of the driver are declared: one
of them is the major number of the driver, the other is a pointer to a region in memory,
memory_buffer, which will be used as storage for the driver data.
The “memory” driver: connection of the device
with its files
In UNIX and Linux, devices are accessed from user space in exactly the same way as files are accessed. These
device files are normally subdirectories of the /dev directory.
To link normal files with a kernel module two numbers are used: major number and minor number.
The major number is the one the kernel uses to link a file with its driver. The minor number is for
Writing device drivers in Linux: A brief tutorial
The “memory” driver: connection of the device with its files 6