Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <linux/init.h>
- #include <linux/module.h>
- #include <linux/i2c.h>
- #include <linux/fs.h>
- #include <linux/kernel.h>
- #include <linux/moduleparam.h>
- #include <linux/kdev_t.h>
- #include <asm/uaccess.h>
- #include <linux/cdev.h>
- #include <linux/string.h>
- #define DEVICE_NAME "simple_driver"
- #define BUFFER_SIZE 10
- static int device_count = 1;
- static dev_t device;
- static struct cdev character_device;
- static int current_buffer_size;
- static char data_buffer[BUFFER_SIZE];
- static ssize_t on_read(struct file *file, char __user *buf, size_t count, loff_t *ppos);
- static ssize_t on_write(struct file *file, char __user *buf, size_t count, loff_t *ppos);
- static long on_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
- static struct file_operations fops =
- {
- .owner = THIS_MODULE,
- .read = on_read,
- .write = on_write,
- .unlocked_ioctl = on_ioctl
- };
- static int __init device_init(void)
- {
- int err;
- /* Say hello */
- pr_info("I just started initalization\n");
- /* Alocate device number, MAJOR & MINOR */
- if (alloc_chrdev_region(&device, 0, device_count, DEVICE_NAME)) {
- pr_warn("Failed to allocate device number\n");
- err =- ENODEV;
- goto err_exit;
- } else {
- pr_info("Device major number: %d, minor number: %d\n", MAJOR(device), MINOR(device));
- }
- /* Register char device */
- cdev_init(&character_device, &fops);
- if (cdev_add(&character_device, device, device_count)) {
- err =- ENODEV;
- goto err_dev_unregister;
- }
- return 0;
- err_dev_unregister:
- unregister_chrdev_region(device, device_count);
- err_exit:
- return err;
- }
- static void __exit device_exit(void)
- {
- cdev_del(&character_device);
- unregister_chrdev_region(device, device_count);
- }
- static ssize_t on_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) {
- int bytes_to_read = (current_buffer_size < count) ? current_buffer_size : count;
- current_buffer_size = 0;
- if (copy_to_user(buf, data_buffer, bytes_to_read)) {
- return -EFAULT;
- }
- return bytes_to_read;
- }
- static ssize_t on_write(struct file *file, char __user *buf, size_t count, loff_t *ppos) {
- if (copy_from_user(data_buffer, buf, count)) {
- return -EFAULT;
- }
- current_buffer_size = count;
- return count;
- }
- static long on_ioctl(struct file *file, unsigned int cmd, unsigned long arg) {
- switch (cmd) {
- case 0:
- pr_warn("Command 0 called\n");
- break;
- default:
- return -ENOTTY;
- break;
- }
- return 0;
- }
- module_init(device_init);
- module_exit(device_exit);
- MODULE_LICENSE("GPL");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement