forked from Light-Dedup/Light-Dedup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic_cache.c
59 lines (53 loc) · 1.44 KB
/
generic_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
/*
* Generic cache.
*
* Copyright (c) 2020-2023 Jiansheng Qiu <[email protected]>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include "generic_cache.h"
#include <linux/slab.h>
void generic_cache_init(struct generic_cache *cache,
struct llist_node *(*allocate)(gfp_t),
void (*free)(struct llist_node *))
{
spin_lock_init(&cache->lock);
init_llist_head(&cache->head);
cache->allocate = allocate;
cache->free = free;
cache->allocated = 0;
}
struct llist_node *generic_cache_alloc(struct generic_cache *cache, gfp_t flags)
{
struct llist_node *ret;
spin_lock(&cache->lock);
if (cache->head.first == NULL) {
cache->allocated += 1;
spin_unlock(&cache->lock);
return cache->allocate(flags);
}
ret = cache->head.first;
cache->head.first = ret->next;
spin_unlock(&cache->lock);
return ret;
}
void generic_cache_free(struct generic_cache *cache, struct llist_node *node)
{
spin_lock(&cache->lock);
node->next = cache->head.first;
cache->head.first = node;
spin_unlock(&cache->lock);
}
// Make sure that there is no other threads accessing it
void generic_cache_destroy(struct generic_cache *cache)
{
struct llist_node *cur = cache->head.first, *next;
printk("Generic cache allocated %lu\n", cache->allocated);
while (cur != NULL) {
next = cur->next;
cache->free(cur);
cur = next;
}
}