1 // SPDX-License-Identifier: LGPL-2.1-or-later
3 * Copyright (C) 2020-2021 Paul Cercueil <paul@crapouillou.net>
6 #include "blockcache.h"
8 #include "lightrec-private.h"
9 #include "memmanager.h"
15 #include <stdatomic.h>
21 struct slist_elm slist;
25 struct lightrec_state *state;
26 pthread_mutex_t mutex;
27 struct slist_elm reap_list;
32 struct reaper *lightrec_reaper_init(struct lightrec_state *state)
34 struct reaper *reaper;
37 reaper = lightrec_malloc(state, MEM_FOR_LIGHTREC, sizeof(*reaper));
39 pr_err("Cannot create reaper: Out of memory\n");
43 reaper->state = state;
45 slist_init(&reaper->reap_list);
47 ret = pthread_mutex_init(&reaper->mutex, NULL);
49 pr_err("Cannot init mutex variable: %d\n", ret);
50 lightrec_free(reaper->state, MEM_FOR_LIGHTREC,
51 sizeof(*reaper), reaper);
58 void lightrec_reaper_destroy(struct reaper *reaper)
60 pthread_mutex_destroy(&reaper->mutex);
61 lightrec_free(reaper->state, MEM_FOR_LIGHTREC, sizeof(*reaper), reaper);
64 int lightrec_reaper_add(struct reaper *reaper, reap_func_t f, void *data)
66 struct reaper_elm *reaper_elm;
67 struct slist_elm *elm;
70 pthread_mutex_lock(&reaper->mutex);
72 for (elm = reaper->reap_list.next; elm; elm = elm->next) {
73 reaper_elm = container_of(elm, struct reaper_elm, slist);
75 if (reaper_elm->data == data)
79 reaper_elm = lightrec_malloc(reaper->state, MEM_FOR_LIGHTREC,
82 pr_err("Cannot add reaper entry: Out of memory\n");
88 reaper_elm->data = data;
89 slist_append(&reaper->reap_list, &reaper_elm->slist);
92 pthread_mutex_unlock(&reaper->mutex);
96 static bool lightrec_reaper_can_reap(struct reaper *reaper)
98 return !atomic_load_explicit(&reaper->sem, memory_order_relaxed);
101 void lightrec_reaper_reap(struct reaper *reaper)
103 struct reaper_elm *reaper_elm;
104 struct slist_elm *elm;
106 pthread_mutex_lock(&reaper->mutex);
108 while (lightrec_reaper_can_reap(reaper) &&
109 !!(elm = slist_first(&reaper->reap_list))) {
110 slist_remove(&reaper->reap_list, elm);
111 pthread_mutex_unlock(&reaper->mutex);
113 reaper_elm = container_of(elm, struct reaper_elm, slist);
115 (*reaper_elm->func)(reaper->state, reaper_elm->data);
117 lightrec_free(reaper->state, MEM_FOR_LIGHTREC,
118 sizeof(*reaper_elm), reaper_elm);
120 pthread_mutex_lock(&reaper->mutex);
123 pthread_mutex_unlock(&reaper->mutex);
126 void lightrec_reaper_pause(struct reaper *reaper)
128 atomic_fetch_add_explicit(&reaper->sem, 1, memory_order_relaxed);
131 void lightrec_reaper_continue(struct reaper *reaper)
133 atomic_fetch_sub_explicit(&reaper->sem, 1, memory_order_relaxed);