-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.c
78 lines (71 loc) · 2.09 KB
/
cache.c
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
#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include "cache.h"
#include "dbg.h"
#include "btree.h"
#include <utlist.h>
struct CacheElem *cachei_page_alloc(struct CacheBase *cache) {
struct CacheElem *elem = calloc(1, sizeof(struct CacheElem));
check_mem(elem, sizeof(struct CacheElem));
elem->cache = calloc(1, cache->pool->page_size);
elem->prev = calloc(1, cache->pool->page_size);
check_mem(elem->cache, cache->pool->page_size);
pthread_mutex_init(&elem->lock, NULL);
pthread_cond_init(&elem->rw_signal, NULL);
elem->next = elem->rq_next = NULL;
return elem;
error:
exit(-1);
}
int cachei_page_free(struct CacheElem *elem) {
pthread_mutex_destroy(&elem->lock);
pthread_cond_destroy(&elem->rw_signal);
free(elem->cache);
free(elem->prev);
free(elem);
return 0;
}
int cache_init(struct CacheBase *cache, struct PagePool *pool, size_t cache_size) {
pageno_t count = floor(((double)cache_size)/(pool->page_size*2));
cache->cache_size = cache_size;
cache->hash = NULL;
cache->pool = pool;
cache->list_tail = cache->list_head = cachei_page_alloc(cache);
struct CacheElem *elem = NULL;
while (count-- > 0) {
elem = cachei_page_alloc(cache);
elem->next = cache->list_tail;
cache->list_tail = elem;
}
cache_print(cache);
pthread_mutex_init(&cache->readq_lock, NULL);
return 0;
}
int cache_free(struct CacheBase *cache) {
struct CacheElem *el1, *el2;
HASH_ITER(hh, cache->hash, el1, el2) {
HASH_DEL(cache->hash, el1);
}
el1 = cache->list_tail;
while ((el2 = el1)) {
el1 = el2->next;
cachei_page_free(el2);
}
pthread_mutex_destroy(&cache->readq_lock);
cache->list_tail = cache->list_head = NULL;
cache->pool = NULL;
cache->hash = NULL;
return 0;
}
int cache_print(struct CacheBase *cache) {
int count_1 = 0; struct CacheElem *temp;
int count_2 = 0;
LL_COUNT(cache->list_tail, temp, count_1);
LL_FOREACH(cache->list_tail, temp)
if (temp->flag && CACHE_USED) count_2++;
log_info("==================================================");
log_info("Cache stats: (all: %d, used: %d)", count_1, count_2);
log_info("==================================================");
return 0;
}