-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchar_driver.c
More file actions
99 lines (74 loc) · 2.44 KB
/
char_driver.c
File metadata and controls
99 lines (74 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <linux/module.h>
#include <linux/version.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "pratimdevice"
//create a structure for our fake device
struct fake_device{
char data[100];
//struct semaphore sem;
} virtual_device;
struct cdev *mycdev;
// Device_Open tells us whether the device is currently being used
static int Device_Open = 0;
static dev_t first;
// writing the file operations functions
int device_open(struct inode *inode, struct file *filp){
printk(KERN_ALERT "Device was opened \n");
return 0;
}
ssize_t device_read(struct file* filp, char* bufStoreData, size_t bufCount, loff_t*curOffset){
printk(KERN_ALERT " Reading from device \n");
return copy_to_user(bufStoreData, virtual_device.data, bufCount);
}
ssize_t device_write(struct file* filp, const char* bufSourceData, size_t bufCount, loff_t*curOffset){
printk(KERN_ALERT " Writing to device \n");
return copy_from_user(virtual_device.data, bufSourceData, bufCount);
}
int device_close(struct inode *inode, struct file *filp){
printk(KERN_ALERT "Device was closed \n");
return 0;
}
// now writing our file operations structure which tells which functions to
// call when user operates on our device file
struct file_operations fops = {
.owner = THIS_MODULE,
.open = device_open,
.release = device_close,
.write = device_write,
.read = device_read
};
static int __init mychar_init(void){
printk(KERN_ALERT "Start by Registering \n");
if(alloc_chrdev_region(&first, 0, 1, "Pratim") < 0){
printk(KERN_ALERT "Registration FAILED \n");
return -1;
}
printk(KERN_INFO "<MAJOR, MINOR> : <%d, %d> \n", MAJOR(first), MINOR(first) );
//printk(KERN_INFO "\t use ", MAJOR(first), MINOR(first) );
// Now creating the cdev structure
mycdev = cdev_alloc();
mycdev->ops = &fops;
mycdev->owner = THIS_MODULE;
// We created cdev, now assign it to the kernel
// cdev_add(mycdev, dev_num, 1)
if(cdev_add(mycdev, first, 1) < 0){
// Always check for errors
printk(KERN_ALERT "unable to add cdev to kernel \n");
return -1;
}
return 0;
}
static void __exit mychar_exit(void){
cdev_del(mycdev);
unregister_chrdev_region(first, 1);
printk(KERN_ALERT "Device Unregistered \n");
}
module_init(mychar_init);
module_exit(mychar_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Pratim Ugale");
MODULE_DESCRIPTION("My first character driver");