-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.h
105 lines (86 loc) · 2.39 KB
/
buffer.h
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
#include <linux/semaphore.h>
#include "data.h"
DEFINE_MUTEX(buffer_lock);
struct buff {
struct data* result;
int head,tail;
int size;
int count;
struct semaphore sem;
spinlock_t Lock;
};
void init_buffer(struct buff* buffer, int size, struct semaphore *sem, spinlock_t* Lock){
printk(KERN_INFO "Initialisaing the buffer\n");
buffer->tail = 0;
buffer->head = 0;
buffer->count = 0;
buffer->size = size;
sema_init(sem, 0);
spin_lock_init(Lock);
}
int insert_buffer_without_lock(struct buff * buffer, struct data data){
buffer->result[buffer->tail++] = data;
if(buffer->tail >= buffer->size){
buffer->size = 0;
}
return 1;
}
struct data read_fifo_without_lock(struct buff * buffer){
struct data result = buffer->result[buffer->head];
buffer->head--;
if(buffer->head < 0){
buffer->head = 0;
}
return result;
}
int alloc_buffer(struct buff* buffer, int size){
buffer->result = kmalloc(sizeof(struct data)*size, GFP_KERNEL);
if(!buffer->result) {
printk(KERN_DEBUG "ERROR while allocating memory to buffer\n");
return -1;
}
return 0;
}
struct data read_fifo(struct buff * buffer, struct semaphore *sem, spinlock_t* Lock){
unsigned long flag;
int res;
spin_lock_irqsave(Lock, flag );
down(sem);
struct data result = buffer->result[buffer->head];
buffer->head++;
if(buffer->head >= buffer->size){
buffer->head = 0;
buffer->count = buffer->tail;
}
buffer->count--;
spin_unlock_irqrestore(Lock, flag);
printk("Read data from buffer\n");
return result;
}
int insert_buffer(struct buff * buffer, struct data data, struct semaphore *sem, spinlock_t* Lock){
unsigned long flag;
printk("Adding Data to the buffer\n");
spin_lock_irqsave(Lock, flag );
if(buffer->tail >= buffer->size){
//printk("Buffer Overflow!! Overwritting the values\n");
buffer->tail = 0;
}
buffer->result[buffer->tail++] = data;
buffer->count++;
if(buffer->count > buffer->size) buffer->count--;
up(sem);
spin_unlock_irqrestore(Lock, flag);
//printk("Data Added to the buffer\n");
return 1;
}
void clear_buffer(struct buff* buffer, int size, struct semaphore *sem, spinlock_t* Lock) {
unsigned long flag;
spin_lock_irqsave(Lock, flag );
buffer->tail = 0;
buffer->head = 0;
buffer->count = 0;
memset(buffer->result, 0, sizeof(buffer->result));
sema_init(sem, 0);
printk("Buffer is cleared\n");
spin_unlock_irqrestore(Lock, flag);
}