aboutsummaryrefslogtreecommitdiff
path: root/include/kpl/gc.h
blob: 5240c40e506dcf2bb48dc7aacd93fb69cd822c0c (plain)
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
/*
 * KPL Garbage Collector
 */

#pragma once

/*
 * Per thread gc, additions and removals are done by the owner thread
 * Marking can be done by any thread
 */
typedef struct {
    _Atomic size_t gc_cycle_head_additions; // updated by owner thread, checked by any thread
    kpl_object_gc *gc_head, *gc_mark_head; // only can be accessed by owner thread
} kpl_gc;

/*
 * Init
 */
inline void kpl_gc_init(kpl_gc *gc) {
    __atomic_store_n(&gc->gc_cycle_head_additions, 0, __ATOMIC_RELAXED);
    gc->gc_head = gc->gc_mark_head = NULL;
}

/*
 * Create a new gc node and a new kpl_object with object_size
 * Add the node to the gc_head
 * Returns the new kpl_object, which has a pointer to the kpl_gc_object
 * Only owner thread calls this
 */
void *kpl_gc_new(kpl_thread *thread, const kpl_interface *interface, int32_t object_size);

/*
 * Delete an object on gc_head before sweeping
 * *object is the object the gc is tracking NOT a kpl_object_gc
 * Many objects can be removed from the gc before sweep and is done though this
 * *object is not void, force casting to prevent memory errors
 * The object and its gc parent must belong to the thread
 */
void kpl_gc_delete(kpl_thread *thread, kpl_object *object);

/*
 * Mark a gc object
 * Tells gc not to delete object
 */
inline void kpl_gc_mark(kpl_object_gc *object_gc) {
    __atomic_test_and_set(&object_gc->gc_mark, __ATOMIC_SEQ_CST);
}

/*
 * Move gc_head to gc_mark head
 * Need task to traverse task and error queue to mark objects all call kpl_interface_gc_mark_object_fn
 * Has to be called separately from kpl_gc_sweep, other tasks will be running while gc runs
 */
inline void kpl_gc_prepare_sweep(kpl_gc *gc) {
    gc->gc_mark_head = gc->gc_head;
    gc->gc_head = NULL;
    gc->gc_cycle_head_additions = 0;
}

/*
 * Run sweep on unmarked objects on gc_mark_head
 * Clear mark on marked objects and return them to gc_head
 */
void kpl_gc_sweep(kpl_thread *thread);

/*
 * Run delete on all objects on gc_head
 */
void kpl_gc_free(kpl_thread *thread);