nckernel  0.1
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
fat_cache.c
Go to the documentation of this file.
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stddef.h>
5 #include <stdint.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <pthread.h>
9 #include <errno.h>
10 
11 #include <fat_cache.h>
12 
13 struct fat_cache {
14  int handle;
15  int offset;
16  char *buffer;
17  int size;
19 };
20 
21 struct fat_cache *create_fat_cache(const char *node, int size)
22 {
23  struct fat_cache *cache;
24 
25  cache = malloc(sizeof(*cache));
26  if (!cache) {
27  return NULL;
28  }
29 
30  cache->handle = open(node, O_RDWR);
31  if (cache->handle < 0) {
32  free(cache);
33  return NULL;
34  }
35 
36  cache->buffer = malloc(size);
37  if (!cache->buffer) {
38  close(cache->handle);
39  free(cache);
40  return NULL;
41  }
42 
43  cache->size = size;
44  cache->offset = ~0; /* This is not valid offset */
45  pthread_mutex_init(&cache->mutex, NULL);
46  return cache;
47 }
48 
49 void destroy_fat_cache(struct fat_cache *cache)
50 {
52  free(cache->buffer);
53  close(cache->handle);
54  free(cache);
55 }
56 
58 {
59  int ret = 0;
60 
61  if (cache->size == 0) {
62  printf("Invalid cache size\n");
63  ret = -EINVAL;
64  goto out;
65  }
66 
67  offset = (offset / cache->size) * cache->size;
68 
69  if (cache->offset == offset) {
70  goto out;
71  }
72 
73  ret = lseek(cache->handle, offset, SEEK_SET);
74  if (ret < 0) {
75  goto out;
76  }
77 
78  ret = read(cache->handle, cache->buffer, cache->size);
79  if (ret < 0) {
80  goto out;
81  }
82 
83  cache->offset = offset;
84 
85 out:
86  return ret;
87 }
88 
89 void *fat_cache(struct fat_cache *cache)
90 {
91  return cache->buffer;
92 }
93 
94 int fat_cache_size(struct fat_cache *cache)
95 {
96  return cache->size;
97 }
98 
99 void fat_cache_lock(struct fat_cache *cache)
100 {
101  pthread_mutex_lock(&cache->mutex);
102 }
103 
104 void fat_cache_unlock(struct fat_cache *cache)
105 {
106  pthread_mutex_unlock(&cache->mutex);
107 }
108 
109 /* End of a file */