summaryrefslogtreecommitdiff
path: root/handlers/chardev.c
blob: b16fd5fe8fbc5635d7830954066602d1c42bb21e (plain) (blame)
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <asm/uaccess.h>

#include "chardev.h"

#define SUCCESS		0
#define DEVICE_NAME	"chardev"
#define BUF_LEN		80

static int Major;
static int opened = 0;
static char chardev_buffer[BUF_LEN];
static char* msg_ptr;

void dumb(void)
{
	printk(KERN_INFO "DUMB EXECUTED\n");
}
EXPORT_SYMBOL(dumb);

static struct file_operations fops = {
	.read = device_read,
	.write = device_write,
	.open = device_open,
	.release = device_release
};

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 to cat and echo to the device file.\n");
	printk(KERN_INFO "Remove the device file and module when done.\n");

	return SUCCESS;
}

void cleanup_module(void)
{
	unregister_chrdev(Major, DEVICE_NAME);
}

static int device_open(struct inode* inode, struct file* filp)
{
	static int counter = 0;

	if (opened)
		return -EBUSY;

	opened++;
	if (counter++ == 0)
		sprintf(chardev_buffer, "Come on, write something here :D\n");

	msg_ptr = chardev_buffer;
	try_module_get(THIS_MODULE);

	return SUCCESS;
}

static int device_release(struct inode* inode, struct file* filp)
{
	opened--;

	module_put(THIS_MODULE);

	return 0;
}

static ssize_t device_read(struct file* filp, char* buff, size_t len, loff_t* off)
{
	int bytes = 0;
	char strpid[14];
	snprintf(strpid, 14, "PID: %d", (current->pid));

	if (*msg_ptr == 0)
		return 0;

	while (len-- && *msg_ptr) {
		put_user(*msg_ptr++, buff++);
		bytes++;
	}

	copy_to_user(buff, strpid, 14);
	bytes += 14;
	buff += 14;

	put_user('\n', buff++);
	bytes++;

	return bytes;
}

static ssize_t device_write(struct file* filp, const char* buff, size_t len, loff_t* off)
{
	int bytes = 0;

	if (len > BUF_LEN) {
		printk(KERN_ALERT "Error: dude you tried to overflow my buffer!\n");
		return -ENOBUFS;
	}

	while (len--) {
		get_user(chardev_buffer[bytes], buff++);
		bytes++;
	}
	chardev_buffer[bytes] = '\0';

	msg_ptr = chardev_buffer;
	return bytes;
}

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Guillermo Ramos");