#include /* Needed by all modules */ #include /* Needed for KERN_INFO */ #include /* Needed for the macros */ #include #include #include /* for put_user */ #define DRIVER_AUTHOR "Vurguuzko " #define DRIVER_DESC "A simple driver" #define DEVICE_NAME "vurguuz" #define BUF_LEN 80 /* Max length of the message from the device */ 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 *); static int __init module_start(void); static void __exit module_stop(void); static int myint = 5; static int maj_num; /* Major number assigned to our device driver */ 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, }; static int __init module_start(void) { maj_num = register_chrdev(0, DEVICE_NAME, &fops); if (maj_num < 0) { printk(KERN_ALERT "Registering char device failed with %d\n", maj_num); return maj_num; } printk(KERN_INFO "Hello world. "); printk(KERN_INFO "myint = %d\n", myint); printk(KERN_INFO "I was assigned major number %d. To talk to\n", maj_num); printk(KERN_INFO "the driver, create a dev file with\n"); printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, maj_num); return 0; } static void __exit module_stop(void) { printk(KERN_INFO "Goodbye world.\n"); } 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) { int bytes_read = 0; sprintf(msg, "Random\n"); msg_Ptr = msg; /* * 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 "written \"%s\".\n", buff); return len; } module_param(myint, int, 0); module_init(module_start); module_exit(module_stop); MODULE_LICENSE("GPL"); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC);